Compare commits

..

1 Commits

Author SHA1 Message Date
e229cd0ba7 removed Makefile for moench and integrated the build in CMake 2022-01-24 16:09:18 +01:00
168 changed files with 6976 additions and 12277 deletions

View File

@ -19,7 +19,6 @@ Checks: '*,
-google-readability-braces-around-statements, -google-readability-braces-around-statements,
-modernize-use-trailing-return-type, -modernize-use-trailing-return-type,
-readability-isolate-declaration, -readability-isolate-declaration,
-readability-implicit-bool-conversion,
-llvmlibc-*' -llvmlibc-*'
HeaderFilterRegex: \.h HeaderFilterRegex: \.h

View File

@ -8,8 +8,11 @@ set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
cmake_policy(SET CMP0074 NEW) cmake_policy(SET CMP0074 NEW)
include(cmake/project_version.cmake) include(cmake/project_version.cmake)
#functions to add compiler flags
include(cmake/SlsAddFlag.cmake) include(cmake/SlsAddFlag.cmake)
include(cmake/SlsFindZeroMQ.cmake)
# Include additional modules that are used unconditionally
include(GNUInstallDirs) include(GNUInstallDirs)
# If conda build, always set lib dir to 'lib' # If conda build, always set lib dir to 'lib'
@ -23,7 +26,7 @@ string(TOLOWER "${PROJECT_NAME}" PROJECT_NAME_LOWER)
# Set targets export name (used by slsDetectorPackage and dependencies) # Set targets export name (used by slsDetectorPackage and dependencies)
set(TARGETS_EXPORT_NAME "${PROJECT_NAME_LOWER}-targets") set(TARGETS_EXPORT_NAME "${PROJECT_NAME_LOWER}-targets")
set(namespace "sls::") #set(namespace "${PROJECT_NAME}::")
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH})
@ -34,8 +37,6 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(SLS_MASTER_PROJECT ON) set(SLS_MASTER_PROJECT ON)
endif() endif()
option(SLS_USE_HDF5 "HDF5 File format" OFF) option(SLS_USE_HDF5 "HDF5 File format" OFF)
option(SLS_BUILD_SHARED_LIBRARIES "Build shared libaries" ON) option(SLS_BUILD_SHARED_LIBRARIES "Build shared libaries" ON)
option(SLS_USE_TEXTCLIENT "Text Client" ON) option(SLS_USE_TEXTCLIENT "Text Client" ON)
@ -68,20 +69,6 @@ if(SLS_BUILD_ONLY_MOENCH)
endif() endif()
option(SLS_EXT_BUILD "external build of part of the project" OFF)
if(SLS_EXT_BUILD)
message(STATUS "External build using already installed libraries")
set(SLS_BUILD_SHARED_LIBRARIES OFF CACHE BOOL "Should already exist" FORCE)
set(SLS_USE_TEXTCLIENT OFF CACHE BOOL "Should already exist" FORCE)
set(SLS_USE_DETECTOR OFF CACHE BOOL "Should already exist" FORCE)
set(SLS_USE_RECEIVER OFF CACHE BOOL "Should already exist" FORCE)
set(SLS_USE_RECEIVER_BINARIES OFF CACHE BOOL "Should already exist" FORCE)
set(SLS_MASTER_PROJECT OFF CACHE BOOL "No master proj in case of extbuild" FORCE)
endif()
#Maybe have an option guarding this?
set(SLS_INTERNAL_RAPIDJSON_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/rapidjson)
set(ClangFormat_EXCLUDE_PATTERNS "build/" set(ClangFormat_EXCLUDE_PATTERNS "build/"
"libs/" "libs/"
"slsDetectorCalibration/" "slsDetectorCalibration/"
@ -92,6 +79,9 @@ set(ClangFormat_EXCLUDE_PATTERNS "build/"
${CMAKE_BINARY_DIR}) ${CMAKE_BINARY_DIR})
find_package(ClangFormat) find_package(ClangFormat)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
@ -110,22 +100,10 @@ else()
endif() endif()
if(SLS_EXT_BUILD) #Add two fake libraries to manage options
# Find ourself in case of external build
find_package(slsDetectorPackage ${PROJECT_VERSION} REQUIRED)
endif()
# slsProjectOptions and slsProjectWarnings are used
# to control options for the libraries
if(NOT TARGET slsProjectOptions)
add_library(slsProjectOptions INTERFACE) add_library(slsProjectOptions INTERFACE)
target_compile_features(slsProjectOptions INTERFACE cxx_std_11)
endif()
if (NOT TARGET slsProjectWarnings)
add_library(slsProjectWarnings INTERFACE) add_library(slsProjectWarnings INTERFACE)
target_compile_features(slsProjectOptions INTERFACE cxx_std_11)
target_compile_options(slsProjectWarnings INTERFACE target_compile_options(slsProjectWarnings INTERFACE
-Wall -Wall
-Wextra -Wextra
@ -141,22 +119,7 @@ if (NOT TARGET slsProjectWarnings)
-Wdouble-promotion -Wdouble-promotion
-Werror=return-type -Werror=return-type
) )
# Add or disable warnings depending on if the compiler supports them
# The function checks internally and sets HAS_warning-name
sls_enable_cxx_warning("-Wnull-dereference")
sls_enable_cxx_warning("-Wduplicated-cond")
sls_disable_cxx_warning("-Wclass-memaccess")
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5 AND "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
target_compile_options(slsProjectWarnings INTERFACE
-Wno-missing-field-initializers)
endif()
endif()
if (NOT TARGET slsProjectCSettings)
#Settings for C code #Settings for C code
add_library(slsProjectCSettings INTERFACE) add_library(slsProjectCSettings INTERFACE)
target_compile_options(slsProjectCSettings INTERFACE target_compile_options(slsProjectCSettings INTERFACE
@ -170,8 +133,29 @@ if (NOT TARGET slsProjectCSettings)
-Wdouble-promotion -Wdouble-promotion
-Werror=return-type -Werror=return-type
) )
sls_disable_c_warning("-Wstringop-truncation")
#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() endif()
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()
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5)
target_compile_options(slsProjectWarnings INTERFACE
-Wno-missing-field-initializers)
endif()
endif()
# Add or disable warnings depending on if the compiler supports them
# The function checks internally and sets HAS_warning-name
sls_enable_cxx_warning("-Wnull-dereference")
sls_enable_cxx_warning("-Wduplicated-cond")
sls_disable_cxx_warning("-Wclass-memaccess")
sls_disable_c_warning("-Wstringop-truncation")
if(SLS_USE_SANITIZER) if(SLS_USE_SANITIZER)
@ -186,22 +170,58 @@ if(SLS_TUNE_LOCAL)
endif() endif()
if(SLS_MASTER_PROJECT) #rapidjson
install(TARGETS slsProjectOptions slsProjectWarnings add_library(rapidjson INTERFACE)
target_include_directories(rapidjson INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/libs/rapidjson>
)
# Install fake the libraries
install(TARGETS slsProjectOptions slsProjectWarnings rapidjson
EXPORT "${TARGETS_EXPORT_NAME}" EXPORT "${TARGETS_EXPORT_NAME}"
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
) )
endif()
set(CMAKE_POSITION_INDEPENDENT_CODE ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_INSTALL_RPATH $ORIGIN) set(CMAKE_INSTALL_RPATH $ORIGIN)
# set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
custom_find_zmq() set(ZeroMQ_HINT "" CACHE STRING "Hint where ZeroMQ could be found")
#Adapted from: https://github.com/zeromq/cppzmq/
if (NOT TARGET libzmq)
if(ZeroMQ_HINT)
message(STATUS "Looking for ZeroMQ in: ${ZeroMQ_HINT}")
find_package(ZeroMQ 4
NO_DEFAULT_PATH
HINTS ${ZeroMQ_DIR}
)
else()
find_package(ZeroMQ 4 QUIET)
endif()
# libzmq autotools install: fallback to pkg-config
if(NOT ZeroMQ_FOUND)
message(STATUS "CMake libzmq package not found, trying again with pkg-config (normal install of zeromq)")
list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/libzmq-pkg-config)
find_package(ZeroMQ 4 REQUIRED)
endif()
# TODO "REQUIRED" above should already cause a fatal failure if not found, but this doesn't seem to work
if(NOT ZeroMQ_FOUND)
message(FATAL_ERROR "ZeroMQ was not found, neither as a CMake package nor via pkg-config")
endif()
if (ZeroMQ_FOUND AND NOT TARGET libzmq)
message(FATAL_ERROR "ZeroMQ version not supported!")
endif()
endif()
get_target_property(VAR libzmq INTERFACE_INCLUDE_DIRECTORIES)
message(STATUS "zmq: ${VAR}")
if (SLS_USE_TESTS) if (SLS_USE_TESTS)
enable_testing() enable_testing()
@ -209,9 +229,8 @@ if (SLS_USE_TESTS)
endif(SLS_USE_TESTS) endif(SLS_USE_TESTS)
if(NOT SLS_EXT_BUILD) # Common functionallity to detector and receiver
add_subdirectory(slsSupportLib) add_subdirectory(slsSupportLib)
endif()
if (SLS_USE_DETECTOR OR SLS_USE_TEXTCLIENT) if (SLS_USE_DETECTOR OR SLS_USE_TEXTCLIENT)
add_subdirectory(slsDetectorSoftware) add_subdirectory(slsDetectorSoftware)
@ -235,7 +254,7 @@ endif (SLS_USE_INTEGRATION_TESTS)
if (SLS_USE_PYTHON) if (SLS_USE_PYTHON)
find_package (Python 3.6 COMPONENTS Interpreter Development) find_package (Python 3.6 COMPONENTS Interpreter Development)
add_subdirectory(libs/pybind11 ${CMAKE_BINARY_DIR}/bin/) add_subdirectory(libs/pybind11)
add_subdirectory(python) add_subdirectory(python)
endif(SLS_USE_PYTHON) endif(SLS_USE_PYTHON)
@ -256,7 +275,6 @@ if(SLS_BUILD_DOCS)
endif(SLS_BUILD_DOCS) endif(SLS_BUILD_DOCS)
if(SLS_USE_MOENCH) if(SLS_USE_MOENCH)
add_subdirectory(slsDetectorCalibration/tiffio)
add_subdirectory(slsDetectorCalibration/moenchExecutables) add_subdirectory(slsDetectorCalibration/moenchExecutables)
endif(SLS_USE_MOENCH) endif(SLS_USE_MOENCH)

View File

@ -1,7 +1,7 @@
SLS Detector Package Minor Release 7.0.0 released on 25.11.2021 SLS Detector Package Minor Release 6.1.0 released on 25.11.2021
=============================================================== ===============================================================
This document describes the differences between v7.0.0 and v6.x.x This document describes the differences between v6.1.0 and v6.0.0.
@ -21,54 +21,10 @@ This document describes the differences between v7.0.0 and v6.x.x
- Fixed minor warnings (will fix commandline print of excess packets for missing packets) - Fixed minor warnings (will fix commandline print of excess packets for missing packets)
- ctb slow adcs and any other adcs (other than temp) goes to the control Server - ctb slow adcs and any other adcs (other than temp) goes to the control Server
- number of udp interfaces is 2 for Eiger (CHANGE IN API??)
- added module id for virtual servers into the udp header
- refactoring (rxr)
- fixed patsetbit and patsetmask for moench - fixed patsetbit and patsetmask for moench
- changed default vref of adc9257 to 2V for moench (from 1.33V) - changed default vref of adc9257 to 2V for moench (from 1.33V)
- moench and ctb - can set the starting frame number of next acquisition
- mythen server kernel check incompatible (cet timezone)
- rx_arping
- rx_threadsids max is now 9 (breaking api)
- fixed datastream disabling for eiger. Its only available in 10g mode.
- m3 server crash (vthrehsold dac names were not provided)
- allow vtrim to be interpolated for Eiger settings
- m3 setThresholdEnergy and setAllThresholdEnergy was overwriting gaincaps with settings enum
- can set localhost with virtual server with minimum configuration: (hostname localhost, rx_hostname localhost, udp_dstip auto)
- increases the progress according to listened index. (not processed index)
- current frame index points to listened frame index (not processed index)
- when in discard partial frames or empty mode, the frame number doesnt increase by 1, it increases to that number (so its faster)
- file write disabled by default
- eiger 12 bit mode
- start non blocking acquisition at modular level
- connect master commands to api (allow set master for eiger)
--ignore-config command line
- command line argument 'master' mainly for virtual servers (also master/top for real eiger), only one virtual server for eiger, use command lines for master/top
- stop servers also check for errors at startup( in case it was running with an older version)
- hostname cmd failed when connecting to servers in update mode (ctb, moench, jungfrau, eiger)
- missingpackets signed (negative => extra packets)
- framescaught and frameindex now returns a vector for each port
- progress looks at activated or enabled ports, so progress does not stagnate
- (eiger) disable datastreaming also for virtual servers only for 10g
- missing packets also takes care of disabled ports
- added geometry to metadata
- 10g eiger nextframenumber get fixed.
- stop, able to set nextframenumber to a consistent (max + 1) for all modules if different (eiger/ctb/jungfrau/moench)
- ctb: can set names for all the dacs
- fpga/kernel programming, checks if drive is a special file and not a normal file
- gotthard 25 um image reconstructed in gui and virtual hdf5 (firmware updated for slave to reverse channels)
- master binary file in json format now
- fixed bug introduced in 6.0.0: hdf5 files created 1 file per frame after the initial file which had maxframesperfile
- m3 polarity, interpolation (enables all counters when enabled), pump probe, analog pulsing, digital pulsing
- updatedetectorserver - removes old server current binary pointing to for blackfin
- removing copydetectorserver using tftp
>>>>>>> developer
- registerCallBackRawDataReady and registerCallBackRawDataModifyReady now gives a sls_receiver_header* instead of a char*, and uint32_t to size_t
- registerCallBackStartAcquisition gave incorrect imagesize (+120 bytes). corrected.
- registerCallBackStartAcquisition parameter is a const string reference
- m3 (runnig config second time with tengiga 0, dr !=32, counters !=0x7) calculated incorrect image size expected
- fixed row column indexing (mainly for multi module Jungfrau 2 interfaces )
- eiger gui row indices not flipped anymore (fix in config)
2. Resolved Issues 2. Resolved Issues
================== ==================

View File

@ -1,38 +0,0 @@
function(custom_find_zmq)
set(ZeroMQ_HINT "" CACHE STRING "Hint where ZeroMQ could be found")
#Adapted from: https://github.com/zeromq/cppzmq/
if (NOT TARGET libzmq)
if(ZeroMQ_HINT)
message(STATUS "Looking for ZeroMQ in: ${ZeroMQ_HINT}")
find_package(ZeroMQ 4
NO_DEFAULT_PATH
HINTS ${ZeroMQ_HINT}
)
else()
find_package(ZeroMQ 4 QUIET)
endif()
# libzmq autotools install: fallback to pkg-config
if(ZeroMQ_FOUND)
message(STATUS "Found libzmq using find_package")
else()
message(STATUS "CMake libzmq package not found, trying again with pkg-config (normal install of zeromq)")
list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake/libzmq-pkg-config)
find_package(ZeroMQ 4 REQUIRED)
endif()
# TODO "REQUIRED" above should already cause a fatal failure if not found, but this doesn't seem to work
if(NOT ZeroMQ_FOUND)
message(FATAL_ERROR "ZeroMQ was not found, neither as a CMake package nor via pkg-config")
endif()
if (ZeroMQ_FOUND AND NOT TARGET libzmq)
message(FATAL_ERROR "ZeroMQ version not supported!")
endif()
endif()
get_target_property(VAR libzmq IMPORTED_LOCATION)
message(STATUS "Using libzmq: ${VAR}")
endfunction()

View File

@ -1,36 +0,0 @@
#From: https://github.com/zeromq/cppzmq/
set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH ON)
find_package(PkgConfig)
pkg_check_modules(PC_LIBZMQ QUIET libzmq)
set(ZeroMQ_VERSION ${PC_LIBZMQ_VERSION})
find_path(ZeroMQ_INCLUDE_DIR zmq.h
PATHS ${ZeroMQ_DIR}/include
${PC_LIBZMQ_INCLUDE_DIRS}
)
find_library(ZeroMQ_LIBRARY
NAMES zmq
PATHS ${ZeroMQ_DIR}/lib
${PC_LIBZMQ_LIBDIR}
${PC_LIBZMQ_LIBRARY_DIRS}
)
if(ZeroMQ_LIBRARY OR ZeroMQ_STATIC_LIBRARY)
set(ZeroMQ_FOUND ON)
message(STATUS "Found libzmq using PkgConfig")
endif()
set ( ZeroMQ_LIBRARIES ${ZeroMQ_LIBRARY} )
set ( ZeroMQ_INCLUDE_DIRS ${ZeroMQ_INCLUDE_DIR} )
if (NOT TARGET libzmq)
add_library(libzmq UNKNOWN IMPORTED)
set_target_properties(libzmq PROPERTIES
IMPORTED_LOCATION ${ZeroMQ_LIBRARIES}
INTERFACE_INCLUDE_DIRECTORIES ${ZeroMQ_INCLUDE_DIRS})
endif()
include ( FindPackageHandleStandardArgs )
find_package_handle_standard_args ( ZeroMQ DEFAULT_MSG ZeroMQ_LIBRARIES ZeroMQ_INCLUDE_DIRS )

View File

@ -26,7 +26,7 @@ install(FILES
) )
install(FILES install(FILES
"${CMAKE_SOURCE_DIR}/cmake/libzmq-pkg-config/FindZeroMQ.cmake" "${CMAKE_SOURCE_DIR}/libzmq-pkg-config/FindZeroMQ.cmake"
COMPONENT devel COMPONENT devel
DESTINATION ${CMAKE_INSTALL_DIR}/libzmq-pkg-config DESTINATION ${CMAKE_INSTALL_DIR}/libzmq-pkg-config
) )

View File

@ -19,4 +19,4 @@ cp build/install/bin/slsMultiReceiver $PREFIX/bin/.
cp build/install/include/sls/* $PREFIX/include/sls cp build/install/include/sls/* $PREFIX/include/sls
cp -rv build/install/share $PREFIX cp -r build/install/share/ $PREFIX/share

View File

@ -1,6 +1,6 @@
# SPDX-License-Identifier: LGPL-3.0-or-other # SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package # Copyright (C) 2021 Contributors to the SLS Detector Package
#Copy the Moench executables #Copy the Moench executables
mkdir -p $PREFIX/bin mkdir -p $PREFIX/bin
cp build/install/bin/moench* $PREFIX/bin/. cp build/install/bin/moench04ZmqProcess $PREFIX/bin/.
cp build/install/bin/moenchZmqProcess $PREFIX/bin/.

View File

@ -34,7 +34,7 @@ add_executable(ctbGui
ctbAdcs.cpp ctbAdcs.cpp
ctbPattern.cpp ctbPattern.cpp
ctbAcquisition.cpp ctbAcquisition.cpp
${CMAKE_SOURCE_DIR}/slsDetectorCalibration/tiffio/src/tiffIO.cpp ${CMAKE_SOURCE_DIR}/slsDetectorCalibration/tiffIO.cpp
) )
@ -43,7 +43,6 @@ target_include_directories(ctbGui PRIVATE
${CMAKE_SOURCE_DIR}/slsDetectorCalibration/dataStructures ${CMAKE_SOURCE_DIR}/slsDetectorCalibration/dataStructures
${CMAKE_SOURCE_DIR}/slsDetectorCalibration/interpolations ${CMAKE_SOURCE_DIR}/slsDetectorCalibration/interpolations
${CMAKE_SOURCE_DIR}/slsDetectorCalibration/ ${CMAKE_SOURCE_DIR}/slsDetectorCalibration/
${CMAKE_SOURCE_DIR}/slsDetectorCalibration/tiffio/include/
) )
# Headders needed for ROOT dictionary generation # Headders needed for ROOT dictionary generation

View File

@ -21,10 +21,9 @@ fi
if [ -f "$infile" ] if [ -f "$infile" ]
then then
dir=$(dirname $infile) gcc -DINFILE="\"$infile\"" -DOUTFILE="\"$outfile\"" -DOUTFILEBIN="\"$outfilebin\"" -o $exe generator.c ;
gcc -DINFILE="\"$infile\"" -DOUTFILE="\"$outfile\"" -DOUTFILEBIN="\"$outfilebin\"" -o $exe generator.c -I$dir;
echo compiling echo compiling
echo gcc -DINFILE="\"$infile\"" -DOUTFILE="\"$outfile\"" -DOUTFILEBIN="\"$outfilebin\"" -o $exe generator.c -I$dir; echo gcc -DINFILE="\"$infile\"" -DOUTFILE="\"$outfile\"" -DOUTFILEBIN="\"$outfilebin\"" -o $exe generator.c ;
$exe ; $exe ;
echo cleaning echo cleaning
rm $exe rm $exe

View File

@ -45,7 +45,6 @@ int main() {
for (const auto &cmd : commands) { for (const auto &cmd : commands) {
std::ostringstream os; std::ostringstream os;
std::cout << cmd << '\n';
proxy.Call(cmd, {}, -1, slsDetectorDefs::HELP_ACTION, os); proxy.Call(cmd, {}, -1, slsDetectorDefs::HELP_ACTION, os);
auto tmp = os.str().erase(0, cmd.size()); auto tmp = os.str().erase(0, cmd.size());

View File

@ -136,7 +136,7 @@ can use dir()
'__str__', '__subclasshook__', '_adc_register', '_frozen', '__str__', '__subclasshook__', '_adc_register', '_frozen',
'_register', 'acquire', 'adcclk', 'adcphase', 'adcpipeline', '_register', 'acquire', 'adcclk', 'adcphase', 'adcpipeline',
'adcreg', 'asamples', 'auto_comp_disable', 'clearAcquiringFlag', 'adcreg', 'asamples', 'auto_comp_disable', 'clearAcquiringFlag',
'clearBit', 'clearROI', 'client_version', 'config', 'clearBit', 'clearROI', 'client_version', 'config', 'copyDetectorServer',
'counters', 'daclist', 'dacvalues', 'dbitclk', 'dbitphase' ... 'counters', 'daclist', 'dacvalues', 'dbitclk', 'dbitphase' ...
Since the list for Detector is rather long it's an good idea to filter it. Since the list for Detector is rather long it's an good idea to filter it.

View File

@ -5,42 +5,17 @@ Detector Server Upgrade
**Location:** slsDetectorPackage/serverBin/ folder for every release. **Location:** slsDetectorPackage/serverBin/ folder for every release.
.. note ::
For Mythen3, Gotthard2 and Eiger, you need to add scripts to automatically start detector server upon power on. See :ref:`Automatic start<Automatic start servers>` for more details.
.. note ::
Eiger requires a manual reboot. Or killall the servers and restart the new linked one. If you are in the process of updating firmware, then don't reboot yet.
From 6.1.1 and above (no tftp required)
---------------------------------------
#. Program from console
.. code-block:: bash
# the following command copies new server, creates a soft link to xxxDetectorServerxxx
# [Jungfrau][CTB][Moench] also deletes the old server binary and edits initttab to respawn server on reboot
# Then, the detector controller will reboot (except Eiger)
sls_detector_put updatedetectorserver /complete-path-to-binary/xxxDetectorServerxxx
#. Copy the detector server specific config files or any others required to the detector:
.. code-block:: bash
sls_detector_put execcommand "tftp pcxxx -r configxxx -g"
5.0.0 - 6.1.1
--------------
#. Install tftp and copy detector server binary to tftp folder #. Install tftp and copy detector server binary to tftp folder
#. Program from console #. Program from console
.. note ::
These instructions are for upgrades from v5.0.0. For earlier versions, contact us.
.. code-block:: bash .. code-block:: bash
# the following command copies new server from pc tftp folder, creates a soft link to xxxDetectorServerxxx # copies new server from pc tftp folder, creates a soft link to xxxDetectorServerxxx
# [Jungfrau][CTB][Moench] also edits initttab to respawn server on reboot # [Jungfrau][CTB][Moench] also edits initttab to respawn server on reboot
# Then, the detector controller will reboot (except Eiger) # Then, the detector controller will reboot (except Eiger)
sls_detector_put copydetectorserver xxxDetectorServerxxx pcxxx sls_detector_put copydetectorserver xxxDetectorServerxxx pcxxx
@ -52,15 +27,18 @@ From 6.1.1 and above (no tftp required)
sls_detector_put execcommand "tftp pcxxx -r configxxx -g" sls_detector_put execcommand "tftp pcxxx -r configxxx -g"
Troubleshooting with tftp .. note ::
^^^^^^^^^^^^^^^^^^^^^^^^^
For Mythen3, Gotthard2 and Eiger, you need to add scripts to automatically start detector server upon power on. See :ref:`Automatic start<Automatic start servers>` for more details.
.. note ::
Eiger requires a manual reboot. Or killall the servers and restart the new linked one. If you are in the process of updating firmware, then don't reboot yet.
Errors
------
#. tftp write error: There is no space left. Please delete some old binaries and try again. #. tftp write error: There is no space left. Please delete some old binaries and try again.
#. text file busy: You are trying to copy the same server. #. text file busy: You are trying to copy the same server.
Older than 5.0.0
-----------------
Please contact us.

View File

@ -3,33 +3,33 @@
### edit with hostname or IP address of your detector ### edit with hostname or IP address of your detector
############################################ ############################################
#hostname bchip181+ #hostname bchip181+
hostname bchip119.psi.ch hostname bchip181+
############################################# #############################################
### edit with hostname or 1Gbs IP address of your server ### edit with hostname or 1Gbs IP address of your server
############################################ ############################################
rx_hostname mpc2011:1777 rx_hostname mpc2011
############################################# #############################################
### edit with 10 Gbs IP of your server ### edit with 10 Gbs IP of your server
############################################ ############################################
udp_dstip 10.1.2.102 udp_dstip 10.1.1.102
############################################# #############################################
### edit with any number in the subnet of your server (first 3 numbers as above) ### edit with any number in the subnet of your server (first 3 numbers as above)
############################################ ############################################
udp_srcip 10.1.2.19 udp_srcip 10.1.1.19
udp_dstport 32000 udp_dstport 32411
############################################# #############################################
### edit with 10 Gbs IP of your server ### edit with 10 Gbs IP of your server
############################################ ############################################
rx_zmqip 10.1.2.102 rx_zmqip 10.1.1.102
rx_zmqport 77000 rx_zmqport 50003
############################################# #############################################
### edit with 1 Gbs IP of PC where you will run the GUI ### edit with 1 Gbs IP of PC where you will run the GUI
############################################ ############################################
zmqip 129.129.202.132 zmqip 129.129.202.98
zmqport 77001 zmqport 50001
@ -38,7 +38,7 @@ rx_zmqstream 1
frames 1000 frames 100000
period 0.0006 period 0.0006
exptime 0.00035 exptime 0.00035
@ -62,9 +62,3 @@ highvoltage 90
#adcreg 0x14 0x40 #adcreg 0x14 0x40
frames 10
period 0.1
rx_jsonpara subframes 1
rx_jsonpara frameMode raw
rx_jsonpara detectorMode analog

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,27 @@
#From: https://github.com/zeromq/cppzmq/
set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH ON)
find_package(PkgConfig)
pkg_check_modules(PC_LIBZMQ QUIET libzmq)
set(ZeroMQ_VERSION ${PC_LIBZMQ_VERSION})
find_library(ZeroMQ_LIBRARY NAMES libzmq.so libzmq.dylib libzmq.dll
PATHS ${PC_LIBZMQ_LIBDIR} ${PC_LIBZMQ_LIBRARY_DIRS})
find_library(ZeroMQ_STATIC_LIBRARY NAMES libzmq-static.a libzmq.a libzmq.dll.a
PATHS ${PC_LIBZMQ_LIBDIR} ${PC_LIBZMQ_LIBRARY_DIRS})
if(ZeroMQ_LIBRARY OR ZeroMQ_STATIC_LIBRARY)
set(ZeroMQ_FOUND ON)
endif()
if (TARGET libzmq)
# avoid errors defining targets twice
return()
endif()
add_library(libzmq SHARED IMPORTED)
set_property(TARGET libzmq PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${PC_LIBZMQ_INCLUDE_DIRS})
set_property(TARGET libzmq PROPERTY IMPORTED_LOCATION ${ZeroMQ_LIBRARY})
add_library(libzmq-static STATIC IMPORTED ${PC_LIBZMQ_INCLUDE_DIRS})
set_property(TARGET libzmq-static PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${PC_LIBZMQ_INCLUDE_DIRS})
set_property(TARGET libzmq-static PROPERTY IMPORTED_LOCATION ${ZeroMQ_STATIC_LIBRARY})

View File

@ -13,8 +13,8 @@ import subprocess
from parse import remove_comments from parse import remove_comments
allow_bitwise_op = ["M3_GainCaps"]
allow_bitwise_op = ["streamingInterface", "M3_GainCaps"] allow_bitwise_op = ["streamingInterface"]
op_key = {"operator|": "|", op_key = {"operator|": "|",
"operator&" : "&"} "operator&" : "&"}

View File

@ -6,57 +6,49 @@ sls::Detector class. The tool needs the libclang bindings
to be installed. to be installed.
When the Detector API is updated this file should be run When the Detector API is updated this file should be run
manually. manually
""" """
from clang import cindex from clang import cindex
import subprocess import subprocess
import argparse import argparse
import sys
import time
from pathlib import Path
from parse import system_include_paths, clang_format_version
REDC = '\033[91m'
GREENC = '\033[92m'
ENDC = '\033[0m'
def red(msg):
return f'{REDC}{msg}{ENDC}'
def green(msg):
return f'{GREENC}{msg}{ENDC}'
def check_clang_format_version(required_version):
if (ver := clang_format_version()) != required_version:
msg = red(f'Clang format version {required_version} required, detected: {ver}. Bye!')
print(msg)
sys.exit(1)
else:
msg = green(f'Found clang-format version {ver}')
print(msg)
def check_for_compile_commands_json(path):
# print(f"Looking for compile data base in: {path}")
compile_data_base_file = path/'compile_commands.json'
if not compile_data_base_file.exists():
msg = red(f"No compile_commands.json file found in {path}. Bye!")
print(msg)
sys.exit(1)
else:
msg = green(f'Found: {compile_data_base_file}')
print(msg)
from parse import system_include_paths
default_build_path = "/home/l_frojdh/sls/build/" default_build_path = "/home/l_frojdh/sls/build/"
fpath = "../../slsDetectorSoftware/src/Detector.cpp" fpath = "../../slsDetectorSoftware/src/Detector.cpp"
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--build_path",
help="Path to the build database",
type=str,
default=default_build_path,
)
cargs = parser.parse_args()
db = cindex.CompilationDatabase.fromDirectory(cargs.build_path)
index = cindex.Index.create()
args = db.getCompileCommands(fpath)
args = list(iter(args).__next__().arguments)[0:-1]
args = args + "-x c++ --std=c++11".split()
syspath = system_include_paths("clang++")
incargs = ["-I" + inc for inc in syspath]
args = args + incargs
tu = index.parse(fpath, args=args)
m = [] m = []
ag = [] ag = []
lines = [] lines = []
ag2 = [] ag2 = []
cn = [] cn = []
def get_arguments(node): def get_arguments(node):
@ -74,7 +66,7 @@ def get_arguments_with_default(node):
args = [] args = []
for arg in node.get_arguments(): for arg in node.get_arguments():
tokens = [t.spelling for t in arg.get_tokens()] tokens = [t.spelling for t in arg.get_tokens()]
# print(tokens) print(tokens)
if '=' in tokens: if '=' in tokens:
if arg.type.spelling == "sls::Positions": #TODO! automate if arg.type.spelling == "sls::Positions": #TODO! automate
args.append("py::arg() = Positions{}") args.append("py::arg() = Positions{}")
@ -119,67 +111,33 @@ def visit(node):
lines.append( lines.append(
f'.def("{child.spelling}",{fs} &Detector::{child.spelling}{args})' f'.def("{child.spelling}",{fs} &Detector::{child.spelling}{args})'
) )
if cargs.verbose:
print(f'&Detector::{child.spelling}{args})')
cn.append(child) cn.append(child)
for child in node.get_children(): for child in node.get_children():
visit(child) visit(child)
# .def("setRxHostname",
# (void (Detector::*)(const std::string &, Positions)) &
# Detector::setRxHostname,
# py::arg(), py::arg() = Positions{})
# .def("setRxHostname",
# (void (Detector::*)(const std::vector<std::string> &)) &
# Detector::setRxHostname,
# py::arg())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--build_path",
help="Path to the build database",
type=Path,
default=default_build_path,
)
parser.add_argument(
"-v",
"--verbose",
help="more output",
action='store_true',
)
cargs = parser.parse_args()
check_clang_format_version(12)
check_for_compile_commands_json(cargs.build_path)
print("Parsing functions in Detector.h - ", end = "", flush = True)
t0 = time.perf_counter()
#parse functions
db = cindex.CompilationDatabase.fromDirectory(cargs.build_path)
index = cindex.Index.create()
args = db.getCompileCommands(fpath)
args = list(iter(args).__next__().arguments)[0:-1]
args = args + "-x c++ --std=c++11".split()
syspath = system_include_paths("clang++")
incargs = ["-I" + inc for inc in syspath]
args = args + incargs
tu = index.parse(fpath, args=args)
visit(tu.cursor) visit(tu.cursor)
print(green('OK'))
print(f'Parsing took {time.perf_counter()-t0:.3f}s')
print("Read detector_in.cpp - ", end = "")
with open("../src/detector_in.cpp") as f: with open("../src/detector_in.cpp") as f:
data = f.read() data = f.read()
s = "".join(lines) s = "".join(lines)
s += ";" s += ";"
text = data.replace("[[FUNCTIONS]]", s) text = data.replace("[[FUNCTIONS]]", s)
warning = "/* WARINING This file is auto generated any edits might be overwritten without warning */\n\n" warning = "/* WARINING This file is auto generated any edits might be overwritten without warning */\n\n"
print(green("OK"))
print("Writing to detector.cpp - ", end = "")
with open("../src/detector.cpp", "w") as f: with open("../src/detector.cpp", "w") as f:
f.write(warning) f.write(warning)
f.write(text) f.write(text)
print(green('OK'))
# run clang format on the output # run clang format on the output
print('Running clang format on generated source -', end = "")
subprocess.run(["clang-format", "../src/detector.cpp", "-i"]) subprocess.run(["clang-format", "../src/detector.cpp", "-i"])
print(green(" OK"))
print("Changes since last commit:")
subprocess.run(['git', 'diff', '../src/detector.cpp'])

View File

@ -5,12 +5,6 @@ import subprocess
from subprocess import PIPE from subprocess import PIPE
import os import os
def clang_format_version():
p = subprocess.run(['clang-format', '--version'], capture_output = True)
ver = p.stdout.decode().split()[2]
major = int(ver.split('.')[0])
return major
def remove_comments(text): def remove_comments(text):
def replacer(match): def replacer(match):

View File

@ -1,45 +1,43 @@
# SPDX-License-Identifier: LGPL-3.0-or-other # SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package # Copyright (C) 2021 Contributors to the SLS Detector Package
from .detector import Detector, freeze from .detector import Detector
from .utils import element_if_equal from .utils import element_if_equal
from .dacs import DetectorDacs, NamedDacs from .dacs import DetectorDacs
import _slsdet import _slsdet
dacIndex = _slsdet.slsDetectorDefs.dacIndex dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty from .detector_property import DetectorProperty
# class CtbDacs(DetectorDacs): class CtbDacs(DetectorDacs):
# """ """
# Ctb dacs Ctb dacs
# """ """
# _dacs = [('dac0', dacIndex(0), 0, 4000, 1400), _dacs = [('dac0', dacIndex(0), 0, 4000, 1400),
# ('dac1', dacIndex(1), 0, 4000, 1200), ('dac1', dacIndex(1), 0, 4000, 1200),
# ('dac2', dacIndex(2), 0, 4000, 900), ('dac2', dacIndex(2), 0, 4000, 900),
# ('dac3', dacIndex(3), 0, 4000, 1050), ('dac3', dacIndex(3), 0, 4000, 1050),
# ('dac4', dacIndex(4), 0, 4000, 1400), ('dac4', dacIndex(4), 0, 4000, 1400),
# ('dac5', dacIndex(5), 0, 4000, 655), ('dac5', dacIndex(5), 0, 4000, 655),
# ('dac6', dacIndex(6), 0, 4000, 2000), ('dac6', dacIndex(6), 0, 4000, 2000),
# ('dac7', dacIndex(7), 0, 4000, 1400), ('dac7', dacIndex(7), 0, 4000, 1400),
# ('dac8', dacIndex(8), 0, 4000, 850), ('dac8', dacIndex(8), 0, 4000, 850),
# ('dac9', dacIndex(9), 0, 4000, 2000), ('dac9', dacIndex(9), 0, 4000, 2000),
# ('dac10', dacIndex(10), 0, 4000, 2294), ('dac10', dacIndex(10), 0, 4000, 2294),
# ('dac11', dacIndex(11), 0, 4000, 983), ('dac11', dacIndex(11), 0, 4000, 983),
# ('dac12', dacIndex(12), 0, 4000, 1475), ('dac12', dacIndex(12), 0, 4000, 1475),
# ('dac13', dacIndex(13), 0, 4000, 1200), ('dac13', dacIndex(13), 0, 4000, 1200),
# ('dac14', dacIndex(14), 0, 4000, 1600), ('dac14', dacIndex(14), 0, 4000, 1600),
# ('dac15', dacIndex(15), 0, 4000, 1455), ('dac15', dacIndex(15), 0, 4000, 1455),
# ('dac16', dacIndex(16), 0, 4000, 0), ('dac16', dacIndex(16), 0, 4000, 0),
# ('dac17', dacIndex(17), 0, 4000, 1000), ('dac17', dacIndex(17), 0, 4000, 1000),
# ] ]
# _dacnames = [_d[0] for _d in _dacs] _dacnames = [_d[0] for _d in _dacs]
from .utils import element from .utils import element
@freeze
class Ctb(Detector): class Ctb(Detector):
def __init__(self, id = 0): def __init__(self, id = 0):
super().__init__(id) super().__init__(id)
self._frozen = False self._frozen = False
# self._dacs = CtbDacs(self) self._dacs = CtbDacs(self)
self._dacs = NamedDacs(self)
@property @property
def dacs(self): def dacs(self):

View File

@ -36,79 +36,6 @@ class Dac(DetectorProperty):
dacstr = ''.join([f'{item:5d}' for item in self.get()]) dacstr = ''.join([f'{item:5d}' for item in self.get()])
return f'{self.__name__:15s}:{dacstr}' return f'{self.__name__:15s}:{dacstr}'
class NamedDacs:
"""
New implementation of the detector dacs. Used at the momen for
Ctb but should replace the old one for all detectors
"""
_frozen = False
_direct_access = ['_detector', '_current', '_dacnames']
def __init__(self, detector):
self._detector = detector
self._current = 0
self._dacnames = [n.replace(" ", "") for n in detector.getDacNames()]
# # Populate the dacs
for i,name in enumerate(self._dacnames):
#name, enum, low, high, default, detector
setattr(self, name, Dac(name, dacIndex(i), 0, 4000, 1000, detector))
self._frozen = True
# def __getattr__(self, name):
# return self.__getattribute__('_' + name)
def __setattr__(self, name, value):
if not self._frozen:
#durining init we need to be able to set up the class
super().__setattr__(name, value)
else:
#Later we restrict us to manipulate dacs and a few fields
if name in self._direct_access:
super().__setattr__(name, value)
elif name in self._dacnames:
return self.__getattribute__(name).__setitem__(slice(None, None, None), value)
else:
raise AttributeError(f'Dac not found: {name}')
def __next__(self):
if self._current >= len(self._dacnames):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattribute__(self._dacnames[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._dacnames), len(self._detector)))
for i, _d in enumerate(self):
dac_array[i,:] = _d[:]
return dac_array
def to_array(self):
return self.get_asarray()
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 from_array(self, dac_array):
self.set_from_array(dac_array)
class DetectorDacs: class DetectorDacs:
_dacs = [] _dacs = []
@ -123,7 +50,7 @@ class DetectorDacs:
# Index to support iteration # Index to support iteration
self._current = 0 self._current = 0
# Name the attributes? # Populate the dacs
for _d in self._dacs: for _d in self._dacs:
setattr(self, '_'+_d[0], Dac(*_d, detector)) setattr(self, '_'+_d[0], Dac(*_d, detector))
@ -132,9 +59,6 @@ class DetectorDacs:
def __getattr__(self, name): def __getattr__(self, name):
return self.__getattribute__('_' + name) return self.__getattribute__('_' + name)
@property
def dacnames(self):
return [_d[0] for _d in _dacs]
def __setattr__(self, name, value): def __setattr__(self, name, value):
if name in self._dacnames: if name in self._dacnames:

View File

@ -258,7 +258,7 @@ class Detector(CppDetectorApi):
@element @element
def rx_threads(self): def rx_threads(self):
""" """
Get thread ids from the receiver in order of [parent, tcp, listener 0, processor 0, streamer 0, listener 1, processor 1, streamer 1, arping]. Get thread ids from the receiver in order of [parent, tcp, listener 0, processor 0, streamer 0, listener 1, processor 1, streamer 1].
Note Note
----- -----
@ -268,17 +268,6 @@ class Detector(CppDetectorApi):
""" """
return self.getRxThreadIds() return self.getRxThreadIds()
@property
@element
def rx_arping(self):
"""Starts a thread in slsReceiver to arping the interface it is listening every minute. Useful in 10G mode. """
return self.getRxArping()
@rx_arping.setter
def rx_arping(self, value):
ut.set_using_dict(self.setRxArping, value)
@property @property
@element @element
def dr(self): def dr(self):
@ -287,7 +276,7 @@ class Detector(CppDetectorApi):
Note Note
----- -----
[Eiger] Options: 4, 8, 12, 16, 32. If set to 32, also sets clkdivider to 2 (quarter speed), else to 0 (full speed)\n [Eiger] Options: 4, 8, 16, 32. If set to 32, also sets clkdivider to 2 (quarter speed), else to 0 (full speed)\n
[Mythen3] Options: 8, 16, 32 \n [Mythen3] Options: 8, 16, 32 \n
[Jungfrau][Gotthard][Ctb][Moench][Mythen3][Gotthard2] 16 [Jungfrau][Gotthard][Ctb][Moench][Mythen3][Gotthard2] 16
""" """
@ -599,13 +588,13 @@ class Detector(CppDetectorApi):
@property @property
@element @element
def rx_framescaught(self): def rx_framescaught(self):
"""Number of frames caught by each port in receiver.""" """Number of frames caught by receiver."""
return self.getFramesCaught() return self.getFramesCaught()
@property @property
@element @element
def nextframenumber(self): def nextframenumber(self):
"""[Eiger][Jungfrau][Moench][CTB] Next frame number. Stopping acquisition might result in different frame numbers for different modules. """ """[Eiger][Jungfrau] Next frame number. Stopping acquisition might result in different frame numbers for different modules. """
return self.getNextFrameNumber() return self.getNextFrameNumber()
@nextframenumber.setter @nextframenumber.setter
@ -1474,19 +1463,6 @@ class Detector(CppDetectorApi):
def trimval(self, value): def trimval(self, value):
ut.set_using_dict(self.setAllTrimbits, value) ut.set_using_dict(self.setAllTrimbits, value)
@property
@element
def master(self):
"""
[Eiger] Sets half module to master and others to slaves.\n
[Gotthard][Gotthard2][Mythen3][Eiger] Gets if the current module/ half module is master.
"""
return self.getMaster()
@master.setter
def master(self, value):
ut.set_using_dict(self.setMaster, value)
@property @property
@element @element
def lock(self): def lock(self):
@ -1571,16 +1547,8 @@ class Detector(CppDetectorApi):
@property @property
def daclist(self): def daclist(self):
""" """Gets the list of enums for every dac for this detector."""
List of enums for every dac for this detector. return self.getDacList()
:setter: Only implemented for Chiptestboard
"""
return self.getDacNames()
@daclist.setter
def daclist(self, value):
self.setDacNames(value)
@property @property
def dacvalues(self): def dacvalues(self):
@ -1926,13 +1894,13 @@ class Detector(CppDetectorApi):
@property @property
@element @element
def rx_frameindex(self): def rx_frameindex(self):
"""Current frame index received for each port in receiver during acquisition.""" """Current frame index received in receiver during acquisition."""
return self.getRxCurrentFrameIndex() return self.getRxCurrentFrameIndex()
@property @property
@element @element
def rx_missingpackets(self): def rx_missingpackets(self):
"""Gets the number of missing packets for each port in receiver. Negative number denotes extra packets. """ """Gets the number of missing packets for each port in receiver."""
return self.getNumMissingPackets() return self.getNumMissingPackets()
""" """
@ -1945,7 +1913,7 @@ class Detector(CppDetectorApi):
def datastream(self): def datastream(self):
""" """
datastream [left|right] [0, 1] datastream [left|right] [0, 1]
[Eiger] Enables or disables data streaming from left or/and right side of detector for 10GbE mode. 1 (enabled) by default. [Eiger] Enables or disables data streaming from left or/and right side of detector. 1 (enabled) by default.
""" """
result = {} result = {}
for port in [defs.LEFT, defs.RIGHT]: for port in [defs.LEFT, defs.RIGHT]:
@ -2147,21 +2115,6 @@ class Detector(CppDetectorApi):
""" """
return ut.reduce_time(self.getMeasuredSubFramePeriod()) return ut.reduce_time(self.getMeasuredSubFramePeriod())
@property
@element
def top(self):
"""[Eiger] Sets half module to top (1), else bottom.
Note
-----
Advanced Function!
"""
return self.getTop()
@top.setter
def top(self, value):
ut.set_using_dict(self.setTop, value)
""" """
------------------<<<Jungfrau specific>>>------------------------- ------------------<<<Jungfrau specific>>>-------------------------
""" """
@ -3498,60 +3451,10 @@ class Detector(CppDetectorApi):
def readout(self): def readout(self):
""" """
[Mythen3] Starts detector readout. Status changes to TRANSMITTING and automatically returns to idle at the end of readout. Mythen3] Starts detector readout. Status changes to TRANSMITTING and automatically returns to idle at the end of readout.
""" """
self.startDetectorReadout() self.startDetectorReadout()
@property
@element
def polarity(self):
"""[Mythen3] Set positive or negative polarity. Enum: polarity"""
return self.getPolarity()
@polarity.setter
def polarity(self, value):
ut.set_using_dict(self.setPolarity, value)
@property
@element
def interpolation(self):
"""[Mythen3] Enable or disable interpolation. Enabling also enables all counters """
return self.getInterpolation()
@interpolation.setter
def interpolation(self, value):
ut.set_using_dict(self.setInterpolation, value)
@property
@element
def pumpprobe(self):
"""[Mythen3] Enable or disable pump probe mode. """
return self.getPumpProbe()
@pumpprobe.setter
def pumpprobe(self, value):
ut.set_using_dict(self.setPumpProbe, value)
@property
@element
def apulse(self):
"""[Mythen3] Enable or disable analog pulsing. """
return self.getAnalogPulsing()
@apulse.setter
def apulse(self, value):
ut.set_using_dict(self.setAnalogPulsing, value)
@property
@element
def dpulse(self):
"""[Mythen3] Enable or disable digital pulsing. """
return self.getDigitalPulsing()
@dpulse.setter
def dpulse(self, value):
ut.set_using_dict(self.setDigitalPulsing, value)
""" """
---------------------------<<<Debug>>>--------------------------- ---------------------------<<<Debug>>>---------------------------

View File

@ -1,8 +1,8 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
/* WARINING This file is auto generated any edits might be overwritten without /* WARINING This file is auto generated any edits might be overwritten without
* warning */ * warning */
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include <pybind11/chrono.h> #include <pybind11/chrono.h>
#include <pybind11/operators.h> #include <pybind11/operators.h>
#include <pybind11/pybind11.h> #include <pybind11/pybind11.h>
@ -173,12 +173,6 @@ void init_det(py::module &m) {
.def("setFlipRows", .def("setFlipRows",
(void (Detector::*)(bool, sls::Positions)) & Detector::setFlipRows, (void (Detector::*)(bool, sls::Positions)) & Detector::setFlipRows,
py::arg(), py::arg() = Positions{}) py::arg(), py::arg() = Positions{})
.def("getMaster",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getMaster,
py::arg() = Positions{})
.def("setMaster", (void (Detector::*)(bool, int)) & Detector::setMaster,
py::arg(), py::arg())
.def("isVirtualDetectorServer", .def("isVirtualDetectorServer",
(Result<bool>(Detector::*)(sls::Positions) const) & (Result<bool>(Detector::*)(sls::Positions) const) &
Detector::isVirtualDetectorServer, Detector::isVirtualDetectorServer,
@ -476,9 +470,7 @@ void init_det(py::module &m) {
(void (Detector::*)()) & Detector::clearAcquiringFlag) (void (Detector::*)()) & Detector::clearAcquiringFlag)
.def("startReceiver", (void (Detector::*)()) & Detector::startReceiver) .def("startReceiver", (void (Detector::*)()) & Detector::startReceiver)
.def("stopReceiver", (void (Detector::*)()) & Detector::stopReceiver) .def("stopReceiver", (void (Detector::*)()) & Detector::stopReceiver)
.def("startDetector", .def("startDetector", (void (Detector::*)()) & Detector::startDetector)
(void (Detector::*)(sls::Positions)) & Detector::startDetector,
py::arg() = Positions{})
.def("startDetectorReadout", .def("startDetectorReadout",
(void (Detector::*)()) & Detector::startDetectorReadout) (void (Detector::*)()) & Detector::startDetectorReadout)
.def("stopDetector", .def("stopDetector",
@ -493,17 +485,14 @@ void init_det(py::module &m) {
Detector::getReceiverStatus, Detector::getReceiverStatus,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getFramesCaught", .def("getFramesCaught",
(Result<std::vector<int64_t>>(Detector::*)(sls::Positions) const) & (Result<int64_t>(Detector::*)(sls::Positions) const) &
Detector::getFramesCaught, Detector::getFramesCaught,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getNumMissingPackets", .def(
(Result<std::vector<int64_t>>(Detector::*)(sls::Positions) const) & "getNumMissingPackets",
(Result<std::vector<uint64_t>>(Detector::*)(sls::Positions) const) &
Detector::getNumMissingPackets, Detector::getNumMissingPackets,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getRxCurrentFrameIndex",
(Result<std::vector<int64_t>>(Detector::*)(sls::Positions) const) &
Detector::getRxCurrentFrameIndex,
py::arg() = Positions{})
.def("getNextFrameNumber", .def("getNextFrameNumber",
(Result<uint64_t>(Detector::*)(sls::Positions) const) & (Result<uint64_t>(Detector::*)(sls::Positions) const) &
Detector::getNextFrameNumber, Detector::getNextFrameNumber,
@ -776,16 +765,9 @@ void init_det(py::module &m) {
Detector::getRxLastClientIP, Detector::getRxLastClientIP,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getRxThreadIds", .def("getRxThreadIds",
(Result<std::array<pid_t, 9>>(Detector::*)(sls::Positions) const) & (Result<std::array<pid_t, 8>>(Detector::*)(sls::Positions) const) &
Detector::getRxThreadIds, Detector::getRxThreadIds,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getRxArping",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getRxArping,
py::arg() = Positions{})
.def("setRxArping",
(void (Detector::*)(bool, sls::Positions)) & Detector::setRxArping,
py::arg(), py::arg() = Positions{})
.def("getFileFormat", .def("getFileFormat",
(Result<defs::fileFormat>(Detector::*)(sls::Positions) const) & (Result<defs::fileFormat>(Detector::*)(sls::Positions) const) &
Detector::getFileFormat, Detector::getFileFormat,
@ -1015,13 +997,6 @@ void init_det(py::module &m) {
sls::Positions)) & sls::Positions)) &
Detector::setDataStream, Detector::setDataStream,
py::arg(), py::arg(), py::arg() = Positions{}) py::arg(), py::arg(), py::arg() = Positions{})
.def("getTop",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getTop,
py::arg() = Positions{})
.def("setTop",
(void (Detector::*)(bool, sls::Positions)) & Detector::setTop,
py::arg(), py::arg() = Positions{})
.def("getChipVersion", .def("getChipVersion",
(Result<double>(Detector::*)(sls::Positions) const) & (Result<double>(Detector::*)(sls::Positions) const) &
Detector::getChipVersion, Detector::getChipVersion,
@ -1280,6 +1255,10 @@ void init_det(py::module &m) {
(Result<std::array<ns, 3>>(Detector::*)(sls::Positions) const) & (Result<std::array<ns, 3>>(Detector::*)(sls::Positions) const) &
Detector::getGateDelayForAllGates, Detector::getGateDelayForAllGates,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getMaster",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getMaster,
py::arg() = Positions{})
.def("getChipStatusRegister", .def("getChipStatusRegister",
(Result<int>(Detector::*)(sls::Positions) const) & (Result<int>(Detector::*)(sls::Positions) const) &
Detector::getChipStatusRegister, Detector::getChipStatusRegister,
@ -1290,46 +1269,6 @@ void init_det(py::module &m) {
.def("getGainCaps", .def("getGainCaps",
(Result<int>(Detector::*)(sls::Positions)) & Detector::getGainCaps, (Result<int>(Detector::*)(sls::Positions)) & Detector::getGainCaps,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getPolarity",
(Result<defs::polarity>(Detector::*)(sls::Positions) const) &
Detector::getPolarity,
py::arg() = Positions{})
.def("setPolarity",
(void (Detector::*)(defs::polarity, sls::Positions)) &
Detector::setPolarity,
py::arg(), py::arg() = Positions{})
.def("getInterpolation",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getInterpolation,
py::arg() = Positions{})
.def("setInterpolation",
(void (Detector::*)(bool, sls::Positions)) &
Detector::setInterpolation,
py::arg(), py::arg() = Positions{})
.def("getPumpProbe",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getPumpProbe,
py::arg() = Positions{})
.def("setPumpProbe",
(void (Detector::*)(bool, sls::Positions)) &
Detector::setPumpProbe,
py::arg(), py::arg() = Positions{})
.def("getAnalogPulsing",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getAnalogPulsing,
py::arg() = Positions{})
.def("setAnalogPulsing",
(void (Detector::*)(bool, sls::Positions)) &
Detector::setAnalogPulsing,
py::arg(), py::arg() = Positions{})
.def("getDigitalPulsing",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getDigitalPulsing,
py::arg() = Positions{})
.def("setDigitalPulsing",
(void (Detector::*)(bool, sls::Positions)) &
Detector::setDigitalPulsing,
py::arg(), py::arg() = Positions{})
.def("getNumberOfAnalogSamples", .def("getNumberOfAnalogSamples",
(Result<int>(Detector::*)(sls::Positions) const) & (Result<int>(Detector::*)(sls::Positions) const) &
Detector::getNumberOfAnalogSamples, Detector::getNumberOfAnalogSamples,
@ -1467,19 +1406,6 @@ void init_det(py::module &m) {
(void (Detector::*)(bool, sls::Positions)) & (void (Detector::*)(bool, sls::Positions)) &
Detector::setLEDEnable, Detector::setLEDEnable,
py::arg(), py::arg() = Positions{}) py::arg(), py::arg() = Positions{})
.def("setDacNames",
(void (Detector::*)(const std::vector<std::string>)) &
Detector::setDacNames,
py::arg())
.def("getDacNames", (std::vector<std::string>(Detector::*)() const) &
Detector::getDacNames)
.def("getDacIndex",
(defs::dacIndex(Detector::*)(const std::string &)) &
Detector::getDacIndex,
py::arg())
.def("getDacName",
(std::string(Detector::*)(defs::dacIndex)) & Detector::getDacName,
py::arg())
.def("setPattern", .def("setPattern",
(void (Detector::*)(const std::string &, sls::Positions)) & (void (Detector::*)(const std::string &, sls::Positions)) &
Detector::setPattern, Detector::setPattern,
@ -1584,13 +1510,17 @@ void init_det(py::module &m) {
Detector::setAdditionalJsonParameter, Detector::setAdditionalJsonParameter,
py::arg(), py::arg(), py::arg() = Positions{}) py::arg(), py::arg(), py::arg() = Positions{})
.def("programFPGA", .def("programFPGA",
(void (Detector::*)(const std::string &, const bool, (void (Detector::*)(const std::string &, sls::Positions)) &
sls::Positions)) &
Detector::programFPGA, Detector::programFPGA,
py::arg(), py::arg(), py::arg() = Positions{}) py::arg(), py::arg() = Positions{})
.def("resetFPGA", .def("resetFPGA",
(void (Detector::*)(sls::Positions)) & Detector::resetFPGA, (void (Detector::*)(sls::Positions)) & Detector::resetFPGA,
py::arg() = Positions{}) py::arg() = Positions{})
.def("copyDetectorServer",
(void (Detector::*)(const std::string &, const std::string &,
sls::Positions)) &
Detector::copyDetectorServer,
py::arg(), py::arg(), py::arg() = Positions{})
.def("updateDetectorServer", .def("updateDetectorServer",
(void (Detector::*)(const std::string &, sls::Positions)) & (void (Detector::*)(const std::string &, sls::Positions)) &
Detector::updateDetectorServer, Detector::updateDetectorServer,
@ -1617,7 +1547,7 @@ void init_det(py::module &m) {
Detector::getUpdateMode, Detector::getUpdateMode,
py::arg() = Positions{}) py::arg() = Positions{})
.def("setUpdateMode", .def("setUpdateMode",
(void (Detector::*)(const bool, sls::Positions)) & (void (Detector::*)(bool, sls::Positions)) &
Detector::setUpdateMode, Detector::setUpdateMode,
py::arg(), py::arg() = Positions{}) py::arg(), py::arg() = Positions{})
.def("readRegister", .def("readRegister",
@ -1709,5 +1639,9 @@ void init_det(py::module &m) {
Detector::getMeasurementTime, Detector::getMeasurementTime,
py::arg() = Positions{}) py::arg() = Positions{})
.def("getUserDetails", .def("getUserDetails",
(std::string(Detector::*)() const) & Detector::getUserDetails); (std::string(Detector::*)() const) & Detector::getUserDetails)
.def("getRxCurrentFrameIndex",
(Result<uint64_t>(Detector::*)(sls::Positions) const) &
Detector::getRxCurrentFrameIndex,
py::arg() = Positions{});
} }

View File

@ -273,8 +273,7 @@ void init_enums(py::module &m) {
slsDetectorDefs::timingSourceType::TIMING_EXTERNAL) slsDetectorDefs::timingSourceType::TIMING_EXTERNAL)
.export_values(); .export_values();
py::enum_<slsDetectorDefs::M3_GainCaps>(Defs, "M3_GainCaps", py::enum_<slsDetectorDefs::M3_GainCaps>(Defs, "M3_GainCaps")
py::arithmetic())
.value("M3_C10pre", slsDetectorDefs::M3_GainCaps::M3_C10pre) .value("M3_C10pre", slsDetectorDefs::M3_GainCaps::M3_C10pre)
.value("M3_C15sh", slsDetectorDefs::M3_GainCaps::M3_C15sh) .value("M3_C15sh", slsDetectorDefs::M3_GainCaps::M3_C15sh)
.value("M3_C30sh", slsDetectorDefs::M3_GainCaps::M3_C30sh) .value("M3_C30sh", slsDetectorDefs::M3_GainCaps::M3_C30sh)
@ -315,9 +314,4 @@ void init_enums(py::module &m) {
.value("FIX_G2", slsDetectorDefs::gainMode::FIX_G2) .value("FIX_G2", slsDetectorDefs::gainMode::FIX_G2)
.value("FIX_G0", slsDetectorDefs::gainMode::FIX_G0) .value("FIX_G0", slsDetectorDefs::gainMode::FIX_G0)
.export_values(); .export_values();
py::enum_<slsDetectorDefs::polarity>(Defs, "polarity")
.value("POSITIVE", slsDetectorDefs::polarity::POSITIVE)
.value("NEGATIVE", slsDetectorDefs::polarity::NEGATIVE)
.export_values();
} }

View File

@ -10,7 +10,7 @@
#include "pedestalSubtraction.h" #include "pedestalSubtraction.h"
#include "slsDetectorData.h" #include "slsDetectorData.h"
#include "slsInterpolation.h" #include "slsInterpolation.h"
#include "sls/tiffIO.h" #include "tiffIO.h"
#include <pthread.h> #include <pthread.h>
#ifdef ROOTSPECTRUM #ifdef ROOTSPECTRUM

View File

@ -2,9 +2,49 @@
// Copyright (C) 2021 Contributors to the SLS Detector Package // Copyright (C) 2021 Contributors to the SLS Detector Package
#ifndef MOENCH03T1RECDATANEW_H #ifndef MOENCH03T1RECDATANEW_H
#define MOENCH03T1RECDATANEW_H #define MOENCH03T1RECDATANEW_H
#include "sls/sls_detector_defs.h"
#include "slsDetectorData.h" #include "slsDetectorData.h"
//#define VERSION_V2
/**
@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 */
#ifndef VERSION_V1
uint64_t
packetCaught[8]; /**< is the version number of this structure format */
#endif
} sls_detector_header;
class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> { class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
private: private:
@ -16,9 +56,6 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
double ghost[200][25]; double ghost[200][25];
// Single point of definition if we need to customize
using header = sls::defs::sls_receiver_header;
public: public:
/** /**
Implements the slsReceiverData structure for the moench02 prototype read Implements the slsReceiverData structure for the moench02 prototype read
@ -27,7 +64,8 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
*/ */
moench03T1ReceiverDataNew(int ns = 5000) moench03T1ReceiverDataNew(int ns = 5000)
: slsDetectorData<uint16_t>(400, 400, ns * 2 * 32 + sizeof(header)), : slsDetectorData<uint16_t>(400, 400,
ns * 2 * 32 + sizeof(sls_detector_header)),
nSamples(ns) { nSamples(ns) {
int nadc = 32; int nadc = 32;
@ -62,15 +100,15 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
} else { } else {
row = 200 + i / sc_width; row = 200 + i / sc_width;
} }
dataMap[row][col] = sizeof(header) + dataMap[row][col] = sizeof(sls_detector_header) +
(nadc * i + iadc) * 2; //+16*(ip+1); (nadc * i + iadc) * 2; //+16*(ip+1);
#ifdef HIGHZ #ifdef HIGHZ
dataMask[row][col] = 0x3fff; // invert data dataMask[row][col] = 0x3fff; // invert data
#endif #endif
if (dataMap[row][col] < 0 || if (dataMap[row][col] < 0 ||
dataMap[row][col] >= nSamples * 2 * 32) dataMap[row][col] >= nSamples * 2 * 32)
std::cout << "Error: pointer " << dataMap[row][col] cout << "Error: pointer " << dataMap[row][col]
<< " out of range " << std::endl; << " out of range " << endl;
} }
} }
} }
@ -82,13 +120,13 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
ghost[iy][ix] = 0.; ghost[iy][ix] = 0.;
int ipacket; int ipacket;
uint ibyte; int ibyte;
int ii = 0; int ii = 0;
for (ibyte = 0; ibyte < sizeof(header) / 2; ibyte++) { for (ibyte = 0; ibyte < sizeof(sls_detector_header) / 2; ibyte++) {
xmap[ibyte] = -1; xmap[ibyte] = -1;
ymap[ibyte] = -1; ymap[ibyte] = -1;
} }
int off = sizeof(header) / 2; int off = sizeof(sls_detector_header) / 2;
for (ipacket = 0; ipacket < npackets; ipacket++) { for (ipacket = 0; ipacket < npackets; ipacket++) {
for (ibyte = 0; ibyte < 8192 / 2; ibyte++) { for (ibyte = 0; ibyte < 8192 / 2; ibyte++) {
i = ipacket * 8208 / 2 + ibyte; i = ipacket * 8208 / 2 + ibyte;
@ -123,7 +161,20 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
required as double required as double
*/ */
double getValue(char *data, int ix, int iy = 0) override { virtual double getValue(char *data, int ix, int iy = 0) {
/* cout << " x "<< ix << " y"<< iy << " val " << getChannel(data, ix,
* iy)<< endl;*/
/* double val=0, vout=getChannel(data, ix, iy); */
/* int x1=ix%25; */
/* for (int ix=0; ix<16; ix++) { */
/* for (int ii=0; ii<2; ii++) { */
/* val+=getChannel(data,x1+25*ix,iy); */
/* val+=getChannel(data,x1+25*ix,399-iy); */
/* } */
/* } */
/* vout+=0.0008*val-6224; */
/* return vout; //(double)getChannel(data, ix, iy);
*/
uint16_t val = getChannel(data, ix, iy) & 0x3fff; uint16_t val = getChannel(data, ix, iy) & 0x3fff;
return val; return val;
}; };
@ -174,9 +225,17 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
*/ */
/* class jfrau_packet_header_t { */
/* public: */
/* unsigned char reserved[4]; */
/* unsigned char packetNumber[1]; */
/* unsigned char frameNumber[3]; */
/* unsigned char bunchid[8]; */
/* }; */
int getFrameNumber(char *buff) { int getFrameNumber(char *buff) {
return ((header *)buff)->detHeader.frameNumber; return ((sls_detector_header *)buff)->frameNumber;
} }; //*((int*)(buff+5))&0xffffff;};
/** /**
@ -188,22 +247,68 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
*/ */
int getPacketNumber(char *buff) { int getPacketNumber(char *buff) {
return ((header *)buff)->detHeader.packetNumber; return ((sls_detector_header *)buff)->packetNumber;
} } //((*(((int*)(buff+4))))&0xff)+1;};
char *readNextFrame(std::ifstream &filebin) override { /* /\** */
/* 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; int ff = -1, np = -1;
return readNextFrame(filebin, ff, np); return readNextFrame(filebin, ff, np);
} };
// not present in base class virtual char *readNextFrame(ifstream &filebin, int &ff) {
virtual char *readNextFrame(std::ifstream &filebin, int &ff) {
int np = -1; int np = -1;
return readNextFrame(filebin, ff, np); return readNextFrame(filebin, ff, np);
}; };
// not present in base class virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) {
virtual char *readNextFrame(std::ifstream &filebin, int &ff, int &np) {
char *data = new char[dataSize]; char *data = new char[dataSize];
char *d = readNextFrame(filebin, ff, np, data); char *d = readNextFrame(filebin, ff, np, data);
if (d == NULL) { if (d == NULL) {
@ -213,10 +318,18 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
return data; return data;
} }
// not present in base class virtual char *readNextFrame(ifstream &filebin, int &ff, int &np,
virtual char *readNextFrame(std::ifstream &filebin, int &ff, int &np,
char *data) { char *data) {
char *retval = 0;
int nd;
int fnum = -1;
np = 0; np = 0;
int pn;
// cout << dataSize << endl;
if (ff >= 0)
fnum = ff;
if (filebin.is_open()) { if (filebin.is_open()) {
if (filebin.read(data, dataSize)) { if (filebin.read(data, dataSize)) {
ff = getFrameNumber(data); ff = getFrameNumber(data);
@ -224,8 +337,8 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
return data; return data;
} }
} }
return nullptr; return NULL;
} };
/** /**
@ -239,7 +352,7 @@ class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
found found
*/ */
char *findNextFrame(char *data, int &ndata, int dsize) override { virtual char *findNextFrame(char *data, int &ndata, int dsize) {
if (dsize < dataSize) if (dsize < dataSize)
ndata = dsize; ndata = dsize;
else else

View File

@ -29,7 +29,7 @@ class moench03T1ZmqDataNew : public slsDetectorData<uint16_t> {
moench03T1ZmqDataNew(int ns = 5000, int oo = 2 * 2) moench03T1ZmqDataNew(int ns = 5000, int oo = 2 * 2)
: slsDetectorData<uint16_t>(400, 400, ns * 32 * 2 + oo), nSamples(ns), : slsDetectorData<uint16_t>(400, 400, ns * 32 * 2 + oo), nSamples(ns),
offset(oo), xtalk(0.00021) { offset(oo), xtalk(0.00021) {
std::cout << "M0.3" << std::endl; cout << "M0.3" << endl;
int nadc = 32; int nadc = 32;
int sc_width = 25; int sc_width = 25;
int sc_height = 200; int sc_height = 200;
@ -70,8 +70,8 @@ class moench03T1ZmqDataNew : public slsDetectorData<uint16_t> {
dataMap[row][col] = dataMap[row][col] =
(nadc * i + iadc) * 2 + offset; //+16*(ip+1); (nadc * i + iadc) * 2 + offset; //+16*(ip+1);
if (dataMap[row][col] < 0 || dataMap[row][col] >= dataSize) if (dataMap[row][col] < 0 || dataMap[row][col] >= dataSize)
std::cout << "Error: pointer " << dataMap[row][col] cout << "Error: pointer " << dataMap[row][col]
<< " out of range " << std::endl; << " out of range " << endl;
} }
} }
} }
@ -260,17 +260,17 @@ class moench03T1ZmqDataNew : public slsDetectorData<uint16_t> {
/* return NULL; */ /* return NULL; */
/* }; */ /* }; */
virtual char *readNextFrame(std::ifstream &filebin) { virtual char *readNextFrame(ifstream &filebin) {
int ff = -1, np = -1; int ff = -1, np = -1;
return readNextFrame(filebin, ff, np); return readNextFrame(filebin, ff, np);
}; };
virtual char *readNextFrame(std::ifstream &filebin, int &ff) { virtual char *readNextFrame(ifstream &filebin, int &ff) {
int np = -1; int np = -1;
return readNextFrame(filebin, ff, np); return readNextFrame(filebin, ff, np);
}; };
virtual char *readNextFrame(std::ifstream &filebin, int &ff, int &np) { virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) {
char *data = new char[32 * 2 * nSamples]; char *data = new char[32 * 2 * nSamples];
char *d = readNextFrame(filebin, ff, np, data); char *d = readNextFrame(filebin, ff, np, data);
if (d == NULL) { if (d == NULL) {
@ -280,7 +280,7 @@ class moench03T1ZmqDataNew : public slsDetectorData<uint16_t> {
return data; return data;
} }
virtual char *readNextFrame(std::ifstream &filebin, int &ff, int &np, virtual char *readNextFrame(ifstream &filebin, int &ff, int &np,
char *data) { char *data) {
// char *retval=0; // char *retval=0;
// int nd; // int nd;

View File

@ -3,9 +3,50 @@
#ifndef MOENCH04ZMQ10GBDATA_H #ifndef MOENCH04ZMQ10GBDATA_H
#define MOENCH04ZMQ10GBDATA_H #define MOENCH04ZMQ10GBDATA_H
#include "slsDetectorData.h" #include "slsDetectorData.h"
#include "sls/sls_detector_defs.h"
using namespace std; #ifndef SLS_DETECTOR_HEADER
#define SLS_DETECTOR_HEADER
//#define VERSION_V2
/**
@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 */
uint64_t
packetCaught[8]; /**< is the version number of this structure format */
} sls_detector_header;
#endif
class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> { class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
private: private:
@ -27,40 +68,67 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
// moench04CtbZmq10GbData(int nas=5000, int nds=0): // moench04CtbZmq10GbData(int nas=5000, int nds=0):
// slsDetectorData<uint16_t>(400, 400, nas*2*32+nds*8), aSamples(nas), // slsDetectorData<uint16_t>(400, 400, nas*2*32+nds*8), aSamples(nas),
// dSamples(nds), nadc(32), sc_width(25), sc_height(200) { // dSamples(nds), nadc(32), sc_width(25), sc_height(200) {
#ifndef RAWDATA
moench04CtbZmq10GbData(int nas = 5000, int nds = 0) moench04CtbZmq10GbData(int nas = 5000, int nds = 0)
: slsDetectorData<uint16_t>(400, 400, : slsDetectorData<uint16_t>(400, 400,
#ifdef RAWDATA (nas > 0) && (nds > 0)
sizeof(slsDetectorDefs::sls_receiver_header) + ? max(nas, nds) * (32 * 2 + 8)
: nas * 32 * 2 + nds * 8),
nadc(32), sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) {
int off = 0;
#endif #endif
#ifdef RAWDATA
moench04CtbZmq10GbData(int nas = 5000, int nds = 0)
: slsDetectorData<uint16_t>(400, 400,
sizeof(sls_detector_header) +
((nas > 0) && (nds > 0) ((nas > 0) && (nds > 0)
? max(nas, nds) * (32 * 2 + 8) ? max(nas, nds) * (32 * 2 + 8)
: nas * 32 * 2 + nds * 8)), : nas * 32 * 2 + nds * 8)),
nadc(32), sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) { nadc(32), sc_width(25), sc_height(200), aSamples(nas),
#ifdef RAWDATA dSamples(nds) {
off=sizeof(slsDetectorDefs::sls_receiver_header); int off = sizeof(sls_detector_header);
#endif cout << "hh" << dataSize << endl;
#ifndef RAWDATA cout << sizeof(sls_detector_header) +
#ifndef CTB ((nas > 0) && (nds > 0) ? max(nas, nds) * (32 * 2 + 8)
off=sizeof(int); : nas * 32 * 2 + nds * 8)
#endif << endl;
#ifdef CTB
off=0;
#endif
#endif #endif
/* int ds; */
/* if (nas && nds) */
/* if (nds>nas) */
/* ds=nds*(32*2+8); */
/* else */
/* ds=nas*(32*2+8); */
/* else */
/* ds=nas*32*2+nds*8; */
cout << "off is " << off << endl; /* new slsDetectorData<uint16_t>(400, 400, ds); */
if (off>0)
cout << "M04 RAW DATA NEW " << endl;
else
cout << "M04 ZMQ DATA NEW " << endl;
int adc_nr[32] = {9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, int adc_nr[32] = {9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3,
2, 5, 4, 7, 6, 23, 22, 21, 20, 19, 18, 2, 5, 4, 7, 6, 23, 22, 21, 20, 19, 18,
17, 16, 31, 30, 29, 28, 27, 26, 25, 24}; 17, 16, 31, 30, 29, 28, 27, 26, 25, 24};
/*
iadc=ptr%32
isample=ptr/32
col=(adc_nr[iadc]%16)*25+isample%25
if (adc_nr[iadc]<16)
row=199-isample/25;
else
row=200+isample/25
adc0 col(9*25..10*25-1) row(199..0)
adc1 col(8*25..9*25-1) row(199..0)
adc2 col(11*25..12*25-1) row(199..0)
adc3 col(10*25..11*25-1) row(199..0)
adc4 col(13*25..14*25-1) row(199..0)
adc5 col(12*25..13*25-1) row(199..0)
adc6 col(15*25..16*25-1) row(199..0)
adc7 col(14*25..15*25-1) row(199..0)
adc8 col(1*25..2*25-1) row(199..0)
*/
int row, col; int row, col;
@ -100,12 +168,40 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
} }
} }
/* for (ibyte=0; ibyte<sizeof(sls_detector_header)/2; ibyte++){ */
/* xmap[ibyte]=-1; */
/* ymap[ibyte]=-1; */
/* } */
/* int off=sizeof(sls_detector_header)/2; */
/* for (ibyte=0; ibyte<dataSize; ibyte++) { */
/* for (ipacket=0; ipacket<npackets; ipacket++) { */
/* for (ibyte=0; ibyte< 8192/2; ibyte++) { */
/* i=ipacket*8208/2+ibyte; */
/* isample=ii/nadc; */
/* if (isample<nSamples) { */
/* iadc=ii%nadc; */
/* adc4 = (int)iadc/4; */
/* ix=isample%sc_width; */
/* iy=isample/sc_width; */
/* if (adc4%2==0) { */
/* xmap[i+off]=adc_nr[iadc]+ix; */
/* ymap[i+off]=ny/2-1-iy; */
/* } else { */
/* xmap[i+off]=adc_nr[iadc]+ix; */
/* ymap[i+off]=ny/2+iy; */
/* } */
/* } */
/* ii++; */
/* // } */
/* } */
/* } */
iframe = 0; iframe = 0;
// cout << "data struct created" << endl; // cout << "data struct created" << endl;
} }
int getGain(char *data, int x, int y) { int getGain(char *data, int x, int y) {
// int aoff=aSamples*2*32; // int aoff=aSamples*2*32;
int irow; int irow;
@ -157,12 +253,10 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
/* unsigned char bunchid[8]; */ /* unsigned char bunchid[8]; */
/* }; */ /* }; */
int getFrameNumber(char *buff) {
#ifdef RAWDATA #ifdef RAWDATA
return ((slsDetectorDefs::sls_receiver_header *)buff)->detHeader.frameNumber; int getFrameNumber(char *buff) {
#endif return ((sls_detector_header *)buff)->frameNumber;
return (int)(*buff); }; //*((int*)(buff+5))&0xffffff;};
};
/** /**
@ -174,15 +268,76 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
*/ */
int getPacketNumber(char *buff) { int getPacketNumber(char *buff) {
#ifdef RAWDATA return ((sls_detector_header *)buff)->packetNumber;
return ((slsDetectorDefs::sls_receiver_header *)buff)->detHeader.packetNumber; } //((*(((int*)(buff+4))))&0xff)+1;};
#endif #endif
return 0; #ifndef RAWDATA
} int getFrameNumber(char *buff) {
return iframe;
}; //((sls_detector_header*)buff)->frameNumber;};//*((int*)(buff+5))&0xffffff;};
#endif
/**
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) { virtual char *readNextFrame(ifstream & filebin) {
int ff = -1, np = -1; int ff = -1, np = -1;
return readNextFrame(filebin, ff, np); return readNextFrame(filebin, ff, np);
@ -203,12 +358,11 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
return data; return data;
} }
#ifndef RAWDATA
virtual char *readNextFrame(ifstream & filebin, int &ff, int &np, virtual char *readNextFrame(ifstream & filebin, int &ff, int &np,
char *data) { char *data) {
// char *retval=0; // char *retval=0;
#ifndef RAWDATA
// int nd; // int nd;
// int fnum = -1; // int fnum = -1;
np = 0; np = 0;
@ -226,13 +380,19 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
} }
} }
return NULL; return NULL;
};
#endif #endif
#ifdef RAWDATA #ifdef RAWDATA
//int nd;
virtual char *readNextFrame(ifstream & filebin, int &ff, int &np,
char *data) {
char *retval = 0;
int nd;
int fnum = -1; int fnum = -1;
np = 0; np = 0;
//int pn; int pn;
// cout << dataSize << endl; // cout << dataSize << endl;
if (ff >= 0) if (ff >= 0)
@ -246,9 +406,9 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
} }
} }
return NULL; return NULL;
};
#endif #endif
};
/** /**
@ -273,4 +433,3 @@ class moench04CtbZmq10GbData : public slsDetectorData<uint16_t> {
}; };
#endif #endif

View File

@ -1,216 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#ifndef MOENCHDATA_H
#define MOENCHDATA_H
#include "slsDetectorData.h"
#include "sls/sls_detector_defs.h"
using namespace std;
class moenchData : public slsDetectorData<uint16_t> {
private:
int iframe;
int nadc;
int sc_width;
int sc_height;
const int aSamples;
const int dSamples;
int off;
int *adc_nr;
int *ibit;
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
*/
moenchData(int off, int nadc_i, int *adc_nr_in, int *ibit_in, int nas = 5000, int nds = 0, int nx_i=400, int ny_i=400)
: nadc(nadc_i), slsDetectorData<uint16_t>(nx_i, ny_i,off+((nas > 0) && (nds > 0)
? max(nas, nds) * (nadc_i * 2 + 8)
: nas * nadc_i * 2 + nds * 8)),
sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) {
adc_nr=new int[nadc];
if (ibit_in)
ibit=new int[nadc];
else
ibit=NULL;
for (iadc=0; iadc<nadc; iadc++) {
adc_nr[iadc]=adc_nr_in[iadc];
if (ibit)
ibit[iadc]=ibit_in[iadc];
}
int row, col;
int iadc;
int i;
for (int is = 0; is < aSamples; is++) {
for (iadc = 0; iadc < nadc; iadc++) {
i = is;
// adc4=(int)iadc/4;
if (i < sc_width * sc_height) {
// for (int i=0; i<sc_width*sc_height; i++) {
col = (adc_nr[iadc] % 16) * sc_width + (i % sc_width);
// if (adc4%2==0) {
if (iadc < 16) {
row = 199 - i / sc_width;
} else {
row = 200 + i / sc_width;
}
if (nds > 0)
dataMap[row][col] =
((nadc + 4) * i + iadc) * 2 + off; //+16*(ip+1);
else
dataMap[row][col] =
(nadc * i + iadc) * 2 + off; //+16*(ip+1);
if (dataMap[row][col] < 0 ||
dataMap[row][col] >= aSamples * 2 * 32 + off)
cout << "Error: pointer " << dataMap[row][col]
<< " out of range " << endl;
}
}
}
iframe = 0;
}
virtual int getGain(char *data, int x, int y) {
// int aoff=aSamples*2*32;
if (ibit) {
int irow;
int isc = x / sc_width;
int icol = x % sc_width;
if (y < 200)
irow = sc_height - 1 - y;
else {
irow = y - sc_height;
isc++;
}
int isample = irow * sc_width + icol;
uint64_t sample;
char *ptr;
if (isc < 0 || isc >= 32)
return 0;
if (ibit[isc] < 0 || ibit[isc] >= 64)
return 0;
if (dSamples > isample) {
ptr = data + 32 * (isample + 1) + 8 * isample;
sample = *((uint64_t *)ptr);
if (sample & (1 << ibit[isc]))
return 1;
}
}
return 0;
}
/**
Returns the frame number for the given dataset. Purely virtual func.
\param buff pointer to the dataset
\returns frame number
*/
int getFrameNumber(char *buff) {
return (int* buff)[0];
};
/**
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 0;
}
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 < dataSize)
ndata = dsize;
else
ndata = dataSize;
return data;
}
};
#endif

View File

@ -4,8 +4,11 @@
#define SLSDETECTORDATA_H #define SLSDETECTORDATA_H
#include <fstream> #include <fstream>
#include <inttypes.h>
#include <iostream> #include <iostream>
using namespace std;
template <class dataType> class slsDetectorData { template <class dataType> class slsDetectorData {
protected: protected:
@ -26,6 +29,8 @@ template <class dataType> class slsDetectorData {
public: public:
/** /**
General slsDetectors data structure. Works for data acquired using the General slsDetectors data structure. Works for data acquired using the
slsDetectorReceiver. Can be generalized to other detectors (many virtual slsDetectorReceiver. Can be generalized to other detectors (many virtual
funcs). funcs).
@ -40,115 +45,10 @@ template <class dataType> class slsDetectorData {
is inversion is required) \param dROI Array of size nx*ny. The elements are 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 1s if the channel is good or in the ROI, 0 is bad or out of the ROI. NULL
(default) means all 1s. (default) means all 1s.
*/ */
slsDetectorData(int npx, int npy, int dsize, int **dMap = NULL, slsDetectorData(int npx, int npy, int dsize, int **dMap = NULL,
dataType **dMask = NULL, int **dROI = NULL); dataType **dMask = NULL, int **dROI = NULL)
virtual ~slsDetectorData();
// Virtual functions
virtual int getPointer(int ix, int iy) { return dataMap[iy][ix]; };
virtual void getPixel(int ip, int &x, int &y);
virtual dataType **getData(char *ptr, int dsize = -1);
virtual double **getImage(char *ptr, int dsize = -1);
virtual dataType getChannel(char *data, int ix, int iy = 0);
virtual int getGain(char *data, int ix, int iy = 0) { return 0; };
virtual double getValue(char *data, int ix, int iy = 0) {
return (double)getChannel(data, ix, iy);
};
virtual int getFrameNumber(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) = 0;
//Returns a pointer to the next complete frame, if none found nullptr
//data needs to be deallocated by caller
virtual char *readNextFrame(std::ifstream &filebin) = 0;
//END Virtual functions
/**
defines the data map (as offset) - no error checking if datasize and
offsets are compatible! \param dMap array of size nx*ny storing the
pointers to the data in the dataset (as offset). If NULL (default),the
data are arranged as if read out row by row
(dataMap[iy][ix]=(iy*nx+ix)*sizeof(dataType);)
*/
void setDataMap(int **dMap = NULL);
/**
defines the data mask i.e. the polarity of the data
\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)
*/
void setDataMask(dataType **dMask = NULL);
/**
defines the region of interest and/or the bad channels mask
\param dROI Array of size nx*ny. The ements are 1s if the channel is
good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all
1s.
*/
void setDataROIMask(int **dROI = NULL);
/**
Define bad channel or roi mask for a single channel
\param ix channel x coordinate
\param iy channel y coordinate (1 for strips)
\param i 1 if pixel is good (or in the roi), 0 if bad
\returns 1 if pixel is good, 0 if it's bad, -1 if pixel is out of range
*/
int setGood(int ix, int iy, int i = 1);
// returns 1 if pixel is good, 0 if it's bad, -1 if pixel is out of range
int isGood(int ix, int iy);
// returns total number of channels, outparam npx and npy x,y dimensions
int getDetectorSize(int &npx, int &npy);
/** Returns the size of the data frame */
int getDataSize() { return dataSize; };
/** changes the size of the data frame */
int setDataSize(int d) {
dataSize = d;
return dataSize;
};
void newFrame() { isOrdered = 0; };
/**
Returns the value of the selected channel for the given dataset. Virtual
function, can be overloaded. \param data pointer to the dataset
(including headers etc) \param ix pixel number in the x direction \param
iy pixel number in the y direction \returns data for the selected
channel, with inversion if required
*/
};
template <typename dataType>
slsDetectorData<dataType>::slsDetectorData(int npx, int npy, int dsize,
int **dMap, dataType **dMask,
int **dROI)
: nx(npx), ny(npy), dataSize(dsize), orderedData(NULL), isOrdered(0) { : nx(npx), ny(npy), dataSize(dsize), orderedData(NULL), isOrdered(0) {
int el = dsize / sizeof(dataType); int el = dsize / sizeof(dataType);
@ -178,7 +78,7 @@ slsDetectorData<dataType>::slsDetectorData(int npx, int npy, int dsize,
setDataROIMask(dROI); setDataROIMask(dROI);
} }
template <typename dataType> slsDetectorData<dataType>::~slsDetectorData() { virtual ~slsDetectorData() {
for (int i = 0; i < ny; i++) { for (int i = 0; i < ny; i++) {
delete[] dataMap[i]; delete[] dataMap[i];
delete[] dataMask[i]; delete[] dataMask[i];
@ -191,10 +91,17 @@ template <typename dataType> slsDetectorData<dataType>::~slsDetectorData() {
delete[] orderedData; delete[] orderedData;
delete[] xmap; delete[] xmap;
delete[] ymap; delete[] ymap;
} };
template <typename dataType> virtual int getPointer(int ix, int iy) { return dataMap[iy][ix]; };
void slsDetectorData<dataType>::setDataMap(int **dMap) { /**
defines the data map (as offset) - no error checking if datasize and
offsets are compatible! \param dMap array of size nx*ny storing the
pointers to the data in the dataset (as offset). If NULL (default),the
data are arranged as if read out row by row
(dataMap[iy][ix]=(iy*nx+ix)*sizeof(dataType);)
*/
void setDataMap(int **dMap = NULL) {
int ip = 0; int ip = 0;
int ix, iy; int ix, iy;
@ -226,10 +133,16 @@ void slsDetectorData<dataType>::setDataMap(int **dMap) {
} }
// cout << "nx:" <<nx << " ny:" << ny << endl; // cout << "nx:" <<nx << " ny:" << ny << endl;
} };
template <typename dataType> /**
void slsDetectorData<dataType>::setDataMask(dataType **dMask) { defines the data mask i.e. the polarity of the data
\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)
*/
void setDataMask(dataType **dMask = NULL) {
if (dMask != NULL) { if (dMask != NULL) {
@ -241,10 +154,16 @@ void slsDetectorData<dataType>::setDataMask(dataType **dMask) {
for (int ix = 0; ix < nx; ix++) for (int ix = 0; ix < nx; ix++)
dataMask[iy][ix] = 0; dataMask[iy][ix] = 0;
} }
} };
/**
defines the region of interest and/or the bad channels mask
\param dROI Array of size nx*ny. The lements are 1s if the channel is
good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all
1s.
*/
void setDataROIMask(int **dROI = NULL) {
template <typename dataType>
void slsDetectorData<dataType>::setDataROIMask(int **dROI) {
if (dROI != NULL) { if (dROI != NULL) {
for (int iy = 0; iy < ny; iy++) for (int iy = 0; iy < ny; iy++)
@ -256,38 +175,60 @@ void slsDetectorData<dataType>::setDataROIMask(int **dROI) {
for (int ix = 0; ix < nx; ix++) for (int ix = 0; ix < nx; ix++)
dataROIMask[iy][ix] = 1; dataROIMask[iy][ix] = 1;
} }
} };
template <typename dataType> /**
int slsDetectorData<dataType>::setGood(int ix, int iy, int i) { Define bad channel or roi mask for a single channel
\param ix channel x coordinate
\param iy channel y coordinate (1 for strips)
\param i 1 if pixel is good (or in the roi), 0 if bad
\returns 1 if pixel is good, 0 if it's bad, -1 if pixel is out of range
*/
int setGood(int ix, int iy, int i = 1) {
if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) if (ix >= 0 && ix < nx && iy >= 0 && iy < ny)
dataROIMask[iy][ix] = i; dataROIMask[iy][ix] = i;
return isGood(ix, iy); return isGood(ix, iy);
} };
/**
template <typename dataType> Define bad channel or roi mask for a single channel
int slsDetectorData<dataType>::isGood(int ix, int iy) { \param ix channel x coordinate
\param iy channel y coordinate (1 for strips)
\returns 1 if pixel is good, 0 if it's bad, -1 if pixel is out of range
*/
int isGood(int ix, int iy) {
if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) if (ix >= 0 && ix < nx && iy >= 0 && iy < ny)
return dataROIMask[iy][ix]; return dataROIMask[iy][ix];
else else
return -1; return -1;
}; };
template <typename dataType> /**
int slsDetectorData<dataType>::getDetectorSize(int &npx, int &npy) { Returns detector size in x,y
\param npx reference to number of channels in x
\param npy reference to number of channels in y (will be 1 for strips)
\returns total number of channels
*/
int getDetectorSize(int &npx, int &npy) {
npx = nx; npx = nx;
npy = ny; npy = ny;
return nx * ny; return nx * ny;
} };
template <typename dataType> /** Returns the size of the data frame */
void slsDetectorData<dataType>::getPixel(int ip, int &x, int &y) { int getDataSize() { return dataSize; };
/** changes the size of the data frame */
int setDataSize(int d) {
dataSize = d;
return dataSize;
};
virtual void getPixel(int ip, int &x, int &y) {
x = xmap[ip]; x = xmap[ip];
y = ymap[ip]; y = ymap[ip];
} };
template <typename dataType> virtual dataType **getData(char *ptr, int dsize = -1) {
dataType **slsDetectorData<dataType>::getData(char *ptr, int dsize) {
int el = dsize / sizeof(dataType); int el = dsize / sizeof(dataType);
// dataType **data; // dataType **data;
int ix, iy; int ix, iy;
@ -310,8 +251,9 @@ dataType **slsDetectorData<dataType>::getData(char *ptr, int dsize) {
return orderedData; return orderedData;
} }
template <typename dataType> void newFrame() { isOrdered = 0; };
double **slsDetectorData<dataType>::getImage(char *ptr, int dsize) {
virtual double **getImage(char *ptr, int dsize = -1) {
double **data; double **data;
int ix, iy; int ix, iy;
@ -329,12 +271,23 @@ double **slsDetectorData<dataType>::getImage(char *ptr, int dsize) {
} }
} }
return data; return data;
} };
template <typename dataType>
dataType slsDetectorData<dataType>::getChannel(char *data, int ix, int iy) { /**
Returns the value of the selected channel for the given dataset. Virtual
function, can be overloaded. \param data pointer to the dataset
(including headers etc) \param ix pixel number in the x direction \param
iy pixel number in the y direction \returns data for the selected
channel, with inversion if required
*/
virtual dataType getChannel(char *data, int ix, int iy = 0) {
dataType m = 0, d = 0; dataType m = 0, d = 0;
if (ix >= 0 && ix < nx && iy >= 0 && iy < ny && dataMap[iy][ix] >= 0 && if (ix >= 0 && ix < nx && iy >= 0 && iy < ny && dataMap[iy][ix] >= 0 &&
dataMap[iy][ix] < dataSize) { dataMap[iy][ix] < dataSize) {
// cout << ix << " " << iy << " " ;
// cout << dataMap[ix][iy] << " " << (void*)data << " " <<
// dataSize<< endl;
m = dataMask[iy][ix]; m = dataMask[iy][ix];
if (isOrdered == 0) if (isOrdered == 0)
d = *((dataType *)(data + getPointer(ix, iy))); d = *((dataType *)(data + getPointer(ix, iy)));
@ -344,4 +297,79 @@ dataType slsDetectorData<dataType>::getChannel(char *data, int ix, int iy) {
return d ^ m; return d ^ m;
}; };
virtual int getGain(char *data, int ix, int iy = 0) { return 0; };
/**
Returns the value of the selected channel for the given dataset. Virtual
function, can be overloaded. \param data pointer to the dataset
(including headers etc) \param ix pixel number in the x direction \param
iy pixel number in the y direction \returns data for the selected
channel, with inversion if required or -1 if its a missing packet
*/
virtual int getChannelwithMissingPackets(char *data, int ix, int iy) {
return 0;
};
/**
Returns the value of the selected channel for the given dataset as
double. \param data pointer to the dataset (including headers etc) \param
ix pixel number in the x direction \param iy pixel number in the y
direction \returns data for the selected channel, with inversion if
required as double
*/
virtual double getValue(char *data, int ix, int iy = 0) {
/* cout << " x "<< ix << " y"<< iy << " val " << getChannel(data, ix,
* iy)<< endl;*/
return (double)getChannel(data, ix, iy);
};
/**
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) = 0;
/**
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) = 0;
/**
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) = 0;
};
#endif #endif

View File

@ -149,7 +149,7 @@ class interpolatingDetector : public singlePhotonDetector {
{ {
nph = addFrame(data, val, 1); nph = addFrame(data, val, 1);
if (interp) if (interp)
return interp->getFlatFieldDistribution(); return interp->getFlatField();
else else
return NULL; return NULL;
}; };

View File

@ -238,96 +238,96 @@ class eta2InterpolationBase : public virtual etaInterpolationBase {
// cout <<"******"<< etax << " " << etay << endl; // cout <<"******"<< etax << " " << etay << endl;
return addToFlatFieldDistribution(etax, etay); return addToFlatField(etax, etay);
} }
/* virtual int addToFlatField(double totquad, int quad, double *cl, */ virtual int addToFlatField(double totquad, int quad, double *cl,
/* double &etax, double &etay) { */ double &etax, double &etay) {
/* double cc[2][2]; */ double cc[2][2];
/* int xoff = 0, yoff = 0; */ int xoff = 0, yoff = 0;
/* switch (quad) { */ switch (quad) {
/* case BOTTOM_LEFT: */ case BOTTOM_LEFT:
/* xoff = 0; */ xoff = 0;
/* yoff = 0; */ yoff = 0;
/* break; */ break;
/* case BOTTOM_RIGHT: */ case BOTTOM_RIGHT:
/* xoff = 1; */ xoff = 1;
/* yoff = 0; */ yoff = 0;
/* break; */ break;
/* case TOP_LEFT: */ case TOP_LEFT:
/* xoff = 0; */ xoff = 0;
/* yoff = 1; */ yoff = 1;
/* break; */ break;
/* case TOP_RIGHT: */ case TOP_RIGHT:
/* xoff = 1; */ xoff = 1;
/* yoff = 1; */ yoff = 1;
/* break; */ break;
/* default:; */ default:;
/* } */ }
/* cc[0][0] = cl[xoff + 3 * yoff]; */ cc[0][0] = cl[xoff + 3 * yoff];
/* cc[1][0] = cl[(yoff + 1) * 3 + xoff]; */ cc[1][0] = cl[(yoff + 1) * 3 + xoff];
/* cc[0][1] = cl[yoff * 3 + xoff + 1]; */ cc[0][1] = cl[yoff * 3 + xoff + 1];
/* cc[1][1] = cl[(yoff + 1) * 3 + xoff + 1]; */ cc[1][1] = cl[(yoff + 1) * 3 + xoff + 1];
/* /\* cout << cl[0] << " " << cl[1] << " " << cl[2] << endl; *\/ */ /* cout << cl[0] << " " << cl[1] << " " << cl[2] << endl; */
/* /\* cout << cl[3] << " " << cl[4] << " " << cl[5] << endl; *\/ */ /* cout << cl[3] << " " << cl[4] << " " << cl[5] << endl; */
/* /\* cout << cl[6] << " " << cl[7] << " " << cl[8] << endl; *\/ */ /* cout << cl[6] << " " << cl[7] << " " << cl[8] << endl; */
/* /\* cout <<"******"<<totquad << " " << quad << endl; *\/ */ /* cout <<"******"<<totquad << " " << quad << endl; */
/* /\* cout << cc[0][0]<< " " << cc[0][1] << endl; *\/ */ /* cout << cc[0][0]<< " " << cc[0][1] << endl; */
/* /\* cout << cc[1][0]<< " " << cc[1][1] << endl; *\/ */ /* cout << cc[1][0]<< " " << cc[1][1] << endl; */
/* // calcMyEta(totquad,quad,cl,etax, etay); */ // calcMyEta(totquad,quad,cl,etax, etay);
/* calcEta(totquad, cc, etax, etay); */ calcEta(totquad, cc, etax, etay);
/* // cout <<"******"<< etax << " " << etay << endl; */ // cout <<"******"<< etax << " " << etay << endl;
/* return addToFlatFieldDistribution(etax, etay); */ return addToFlatField(etax, etay);
/* } */ }
////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////
/* virtual int addToFlatField(double *cluster, double &etax, double &etay) { */ virtual int addToFlatField(double *cluster, double &etax, double &etay) {
/* double sDum[2][2]; */ double sDum[2][2];
/* double tot, totquad; */ double tot, totquad;
/* // int corner; */ // int corner;
/* // corner= */ // corner=
/* calcQuad(cluster, tot, totquad, sDum); */ calcQuad(cluster, tot, totquad, sDum);
/* // double xpos_eta,ypos_eta; */ // double xpos_eta,ypos_eta;
/* // double dX,dY; */ // double dX,dY;
/* calcEta(totquad, sDum, etax, etay); */ calcEta(totquad, sDum, etax, etay);
/* return addToFlatField(etax, etay); */ return addToFlatField(etax, etay);
/* }; */ };
/* virtual int addToFlatField(int *cluster, double &etax, double &etay) { */ virtual int addToFlatField(int *cluster, double &etax, double &etay) {
/* double sDum[2][2]; */ double sDum[2][2];
/* double tot, totquad; */ double tot, totquad;
/* // int corner; */ // int corner;
/* // corner= */ // corner=
/* calcQuad(cluster, tot, totquad, sDum); */ calcQuad(cluster, tot, totquad, sDum);
/* // double xpos_eta,ypos_eta; */ // double xpos_eta,ypos_eta;
/* // double dX,dY; */ // double dX,dY;
/* calcEta(totquad, sDum, etax, etay); */ calcEta(totquad, sDum, etax, etay);
/* return addToFlatField(etax, etay); */ return addToFlatField(etax, etay);
/* }; */ };
/* virtual int addToFlatFieldDistribution(double etax, double etay) { */ virtual int addToFlatField(double etax, double etay) {
/* #ifdef MYROOT1 */ #ifdef MYROOT1
/* heta->Fill(etax, etay); */ heta->Fill(etax, etay);
/* #endif */ #endif
/* #ifndef MYROOT1 */ #ifndef MYROOT1
/* int ex, ey; */ int ex, ey;
/* ex = (etax - etamin) / etastepX; */ ex = (etax - etamin) / etastepX;
/* ey = (etay - etamin) / etastepY; */ ey = (etay - etamin) / etastepY;
/* if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0) */ if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0)
/* heta[ey * nbetaX + ex]++; */ heta[ey * nbetaX + ex]++;
/* #endif */ #endif
/* return 0; */ return 0;
/* }; */ };
virtual int *getInterpolatedImage() { virtual int *getInterpolatedImage() {
int ipx, ipy; int ipx, ipy;

View File

@ -205,44 +205,44 @@ class eta3InterpolationBase : public virtual etaInterpolationBase {
double &etay) { double &etay) {
calcEta3(cl, etax, etay, totquad); calcEta3(cl, etax, etay, totquad);
return addToFlatFieldDistribution(etax, etay); return addToFlatField(etax, etay);
} }
/* virtual int addToFlatField(double totquad, int quad, double *cl, */ virtual int addToFlatField(double totquad, int quad, double *cl,
/* double &etax, double &etay) { */ double &etax, double &etay) {
/* calcEta3(cl, etax, etay, totquad); */ calcEta3(cl, etax, etay, totquad);
/* return addToFlatField(etax, etay); */ return addToFlatField(etax, etay);
/* } */ }
////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////
/* virtual int addToFlatField(double *cluster, double &etax, double &etay) { */ virtual int addToFlatField(double *cluster, double &etax, double &etay) {
/* double totquad; */ double totquad;
/* calcEta3(cluster, etax, etay, totquad); */ calcEta3(cluster, etax, etay, totquad);
/* return addToFlatField(etax, etay); */ return addToFlatField(etax, etay);
/* }; */ };
/* virtual int addToFlatField(int *cluster, double &etax, double &etay) { */ virtual int addToFlatField(int *cluster, double &etax, double &etay) {
/* double totquad; */ double totquad;
/* calcEta3(cluster, etax, etay, totquad); */ calcEta3(cluster, etax, etay, totquad);
/* return addToFlatField(etax, etay); */ return addToFlatField(etax, etay);
/* }; */ };
/* virtual int addToFlatField(double etax, double etay) { */ virtual int addToFlatField(double etax, double etay) {
/* #ifdef MYROOT1 */ #ifdef MYROOT1
/* heta->Fill(etax, etay); */ heta->Fill(etax, etay);
/* #endif */ #endif
/* #ifndef MYROOT1 */ #ifndef MYROOT1
/* int ex, ey; */ int ex, ey;
/* ex = (etax - etamin) / etastepX; */ ex = (etax - etamin) / etastepX;
/* ey = (etay - etamin) / etastepY; */ ey = (etay - etamin) / etastepY;
/* if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0) */ if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0)
/* heta[ey * nbetaX + ex]++; */ heta[ey * nbetaX + ex]++;
/* #endif */ #endif
/* return 0; */ return 0;
/* }; */ };
/* protected: */ /* protected: */

View File

@ -3,7 +3,7 @@
#ifndef ETA_INTERPOLATION_ADAPTIVEBINS_H #ifndef ETA_INTERPOLATION_ADAPTIVEBINS_H
#define ETA_INTERPOLATION_ADAPTIVEBINS_H #define ETA_INTERPOLATION_ADAPTIVEBINS_H
#include "sls/tiffIO.h" #include "tiffIO.h"
#include <cmath> #include <cmath>
//#include "etaInterpolationBase.h" //#include "etaInterpolationBase.h"
#include "etaInterpolationPosXY.h" #include "etaInterpolationPosXY.h"

View File

@ -10,7 +10,7 @@
#include <TTree.h> #include <TTree.h>
#endif #endif
#include "slsInterpolation.h" #include "slsInterpolation.h"
#include "sls/tiffIO.h" #include "tiffIO.h"
#include <cmath> #include <cmath>
class etaInterpolationBase : public slsInterpolation { class etaInterpolationBase : public slsInterpolation {
@ -128,7 +128,7 @@ class etaInterpolationBase : public slsInterpolation {
return NULL; return NULL;
}; };
void *readFlatField(const char *imgname, double emin = 1, double emax = 0) { int readFlatField(const char *imgname, double emin = 1, double emax = 0) {
if (emax >= 1) if (emax >= 1)
etamax = emax; etamax = emax;
if (emin <= 0) if (emin <= 0)
@ -169,9 +169,9 @@ class etaInterpolationBase : public slsInterpolation {
} }
} }
delete[] gm; delete[] gm;
return heta; return 1;
} }
return NULL; return 0;
}; };
float *gethhx() { float *gethhx() {
@ -183,17 +183,12 @@ class etaInterpolationBase : public slsInterpolation {
// hhy->Scale((double)nSubPixels); // hhy->Scale((double)nSubPixels);
return hhy; return hhy;
}; };
virtual int addToFlatFieldDistribution(double etax, double etay) { virtual int addToFlatField(double etax, double etay) {
#ifdef MYROOT1
heta->Fill(etax, etay);
#endif
#ifndef MYROOT1
int ex, ey; int ex, ey;
ex = (etax - etamin) / etastepX; ex = (etax - etamin) / etastepX;
ey = (etay - etamin) / etastepY; ey = (etay - etamin) / etastepY;
if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0) if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0)
heta[ey * nbetaX + ex]++; heta[ey * nbetaX + ex]++;
#endif
return 0; return 0;
}; };

View File

@ -3,7 +3,7 @@
#ifndef ETA_INTERPOLATION_CLEVER_ADAPTIVEBINS_H #ifndef ETA_INTERPOLATION_CLEVER_ADAPTIVEBINS_H
#define ETA_INTERPOLATION_CLEVER_ADAPTIVEBINS_H #define ETA_INTERPOLATION_CLEVER_ADAPTIVEBINS_H
#include "sls/tiffIO.h" #include "tiffIO.h"
#include <cmath> #include <cmath>
//#include "etaInterpolationBase.h" //#include "etaInterpolationBase.h"
#include "etaInterpolationAdaptiveBins.h" #include "etaInterpolationAdaptiveBins.h"

View File

@ -3,7 +3,7 @@
#ifndef ETA_INTERPOLATION_POSXY_H #ifndef ETA_INTERPOLATION_POSXY_H
#define ETA_INTERPOLATION_POSXY_H #define ETA_INTERPOLATION_POSXY_H
//#include "sls/tiffIO.h" //#include "tiffIO.h"
#include "eta2InterpolationBase.h" #include "eta2InterpolationBase.h"
#include "eta3InterpolationBase.h" #include "eta3InterpolationBase.h"
#include "etaInterpolationBase.h" #include "etaInterpolationBase.h"

View File

@ -3,7 +3,7 @@
#ifndef ETA_INTERPOLATION_RANDOMBINS_H #ifndef ETA_INTERPOLATION_RANDOMBINS_H
#define ETA_INTERPOLATION_RANDOMBINS_H #define ETA_INTERPOLATION_RANDOMBINS_H
#include "sls/tiffIO.h" #include "tiffIO.h"
//#include "etaInterpolationBase.h" //#include "etaInterpolationBase.h"
#include "etaInterpolationPosXY.h" #include "etaInterpolationPosXY.h"
#include <algorithm> #include <algorithm>

View File

@ -78,20 +78,20 @@ class noInterpolation : public slsInterpolation {
}; };
////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////
/* virtual int addToFlatField(double *cluster, double &etax, double &etay) { */ virtual int addToFlatField(double *cluster, double &etax, double &etay) {
/* return 0; */ return 0;
/* }; */ };
/* virtual int addToFlatField(int *cluster, double &etax, double &etay) { */ virtual int addToFlatField(int *cluster, double &etax, double &etay) {
/* return 0; */ return 0;
/* }; */ };
virtual int addToFlatFieldDistribution(double etax, double etay) { return 0; }; virtual int addToFlatField(double etax, double etay) { return 0; };
/* virtual int addToFlatField(double totquad, int quad, double *cl, */ virtual int addToFlatField(double totquad, int quad, double *cl,
/* double &etax, double &etay) { */ double &etax, double &etay) {
/* return 0; */ return 0;
/* }; */ };
virtual int addToFlatField(double totquad, int quad, int *cl, double &etax, virtual int addToFlatField(double totquad, int quad, int *cl, double &etax,
double &etay) { double &etay) {

View File

@ -5,7 +5,7 @@
#include <cstdlib> #include <cstdlib>
#ifndef MY_TIFF_IO_H #ifndef MY_TIFF_IO_H
#include "sls/tiffIO.h" #include "tiffIO.h"
#endif #endif
#ifndef DEF_QUAD #ifndef DEF_QUAD
@ -175,31 +175,29 @@ class slsInterpolation {
return hint; return hint;
}; };
//virtual int addToFlatField(double *cluster, double &etax, double &etay) = 0; virtual int addToFlatField(double *cluster, double &etax, double &etay) = 0;
//virtual int addToFlatField(int *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, virtual int addToFlatField(double totquad, int quad, int *cl, double &etax,
double &etay) = 0; double &etay) = 0;
//virtual int addToFlatField(double totquad, int quad, double *cluster, virtual int addToFlatField(double totquad, int quad, double *cluster,
// double &etax, double &etay) = 0; double &etax, double &etay) = 0;
virtual int addToFlatFieldDistribution(double etax, double etay) = 0; virtual int addToFlatField(double etax, double etay) = 0;
virtual int *getFlatFieldDistribution() { return NULL; }; virtual int *getFlatField() { return NULL; };
virtual int *setFlatField(int *h, int nbx = -1, int nby = -1, virtual int *setFlatField(int *h, int nb = -1, double emin = -1,
double emin = -1,
double emax = -1) { double emax = -1) {
return NULL; return NULL;
}; };
virtual void *writeFlatField(const char *imgname) { return NULL; }; virtual void *writeFlatField(const char *imgname) { return NULL; };
virtual void *readFlatField(const char *imgname, virtual void *readFlatField(const char *imgname, int nb = -1,
double emin = 1, double emax = 0) { double emin = 1, double emax = 0) {
return NULL; return NULL;
}; };
virtual int *getFlatField(int &nbx, int &nby, double &emin, double &emax) { virtual int *getFlatField(int &nb, double &emin, double &emax) {
nbx = 0; nb = 0;
nby=0;
emin = 0; emin = 0;
emax = 0; emax = 0;
return getFlatFieldDistribution(); return getFlatField();
}; };
virtual void resetFlatField() = 0; virtual void resetFlatField() = 0;

View File

@ -23,7 +23,7 @@
#endif #endif
#include "moench03CommonMode.h" #include "moench03CommonMode.h"
#include "moench03GhostSummation.h" #include "moench03GhostSummation.h"
#include "sls/tiffIO.h" #include "tiffIO.h"
#include <fstream> #include <fstream>
#include <iomanip> #include <iomanip>
#include <sstream> #include <sstream>

View File

@ -20,7 +20,7 @@ class commonModeSubtractionColumn : public commonModeSubtraction {
mean2[iroi] += val * val; mean2[iroi] += val * val;
nCm[iroi]++; nCm[iroi]++;
if (nCm[iroi] > rows) if (nCm[iroi] > rows)
std::cout << "Too many pixels added " << nCm[iroi] << std::endl; cout << "Too many pixels added " << nCm[iroi] << endl;
/* if (ix==10 && iy<20) */ /* if (ix==10 && iy<20) */
/* cout << " ** "<<val << " " << mean[iroi] << " " << /* cout << " ** "<<val << " " << mean[iroi] << " " <<
* nCm[iroi] << " " << getCommonMode(ix, iy) << endl; */ * nCm[iroi] << " " << getCommonMode(ix, iy) << endl; */

View File

@ -1,52 +1,57 @@
# SPDX-License-Identifier: LGPL-3.0-or-other # SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package # Copyright (C) 2021 Contributors to the SLS Detector Package
find_package(TIFF REQUIRED)
set(MOENCH_EXECUTABLES) set(MOENCH_EXECUTABLES)
#Moench ZMQ #Moench ZMQ
add_executable(moench03ZmqProcess moenchZmqProcess.cpp) add_executable(moenchZmqProcess moenchZmqProcess.cpp ../tiffIO.cpp)
target_compile_definitions(moench03ZmqProcess PRIVATE NEWZMQ INTERP) target_compile_definitions(moenchZmqProcess PRIVATE NEWZMQ INTERP)
list(APPEND MOENCH_EXECUTABLES moench03ZmqProcess) list(APPEND MOENCH_EXECUTABLES moenchZmqProcess)
#Moench HighZ ZMQ
add_executable(moenchHighZZmqProcess moenchZmqProcess.cpp)
target_compile_definitions(moenchHighZZmqProcess PRIVATE NEWZMQ INTERP HIGHZ)
list(APPEND MOENCH_EXECUTABLES moenchHighZZmqProcess)
#Moench04 ZMQ #Moench04 ZMQ
add_executable(moench04ZmqProcess moenchZmqProcess.cpp) add_executable(moench04ZmqProcess moenchZmqProcess.cpp ../tiffIO.cpp)
target_compile_definitions(moench04ZmqProcess PRIVATE NEWZMQ INTERP MOENCH04) target_compile_definitions(moench04ZmqProcess PRIVATE NEWZMQ INTERP MOENCH04)
list(APPEND MOENCH_EXECUTABLES moench04ZmqProcess) list(APPEND MOENCH_EXECUTABLES moench04ZmqProcess)
#OFFLINE Processing? #OFFLINE Processing?
add_executable(moench03RawDataProcess moenchRawDataProcess.cpp) add_executable(moenchClusterFinder moench03ClusterFinder.cpp ../tiffIO.cpp)
target_compile_definitions(moench03RawDataProcess PRIVATE) target_compile_definitions(moenchClusterFinder PRIVATE SAVE_ALL NEWRECEIVER)
list(APPEND MOENCH_EXECUTABLES moench03RawDataProcess) list(APPEND MOENCH_EXECUTABLES moenchClusterFinder)
add_executable(moenchHighZRawDataProcess moenchRawDataProcess.cpp) add_executable(moenchClusterFinderHighZ moench03ClusterFinder.cpp ../tiffIO.cpp)
target_compile_definitions(moenchHighZRawDataProcess PRIVATE HIGHZ) target_compile_definitions(moenchClusterFinderHighZ PRIVATE SAVE_ALL NEWRECEIVER HIGHZ)
list(APPEND MOENCH_EXECUTABLES moenchHighZRawDataProcess) list(APPEND MOENCH_EXECUTABLES moenchClusterFinderHighZ)
add_executable(moench04RawDataProcess moenchRawDataProcess.cpp) add_executable(moenchMakeEta moench03Interpolation.cpp ../tiffIO.cpp)
target_compile_definitions(moench04RawDataProcess PRIVATE MOENCH04) target_compile_definitions(moenchMakeEta PRIVATE FF)
list(APPEND MOENCH_EXECUTABLES moench04RawDataProcess) list(APPEND MOENCH_EXECUTABLES moenchMakeEta)
#interpolation stuff add_executable(moenchInterpolation moench03Interpolation.cpp ../tiffIO.cpp)
add_executable(moench03MakeEta moench03Interpolation.cpp)
target_compile_definitions(moench03MakeEta PRIVATE FF)
list(APPEND MOENCH_EXECUTABLES moench03MakeEta)
add_executable(moench03Interpolation moench03Interpolation.cpp)
#no compile defs #no compile defs
list(APPEND MOENCH_EXECUTABLES moench03Interpolation) list(APPEND MOENCH_EXECUTABLES moenchInterpolation)
add_executable(moench03NoInterpolation moench03NoInterpolation.cpp) add_executable(moenchNoInterpolation moench03NoInterpolation.cpp ../tiffIO.cpp)
#no compile defs #no compile defs
list(APPEND MOENCH_EXECUTABLES moench03NoInterpolation) list(APPEND MOENCH_EXECUTABLES moenchNoInterpolation)
add_executable(moenchPhotonCounter moenchPhotonCounter.cpp ../tiffIO.cpp)
target_compile_definitions(moenchPhotonCounter PRIVATE NEWRECEIVER)
list(APPEND MOENCH_EXECUTABLES moenchPhotonCounter)
add_executable(moenchAnalog moenchPhotonCounter.cpp ../tiffIO.cpp)
target_compile_definitions(moenchAnalog PRIVATE NEWRECEIVER ANALOG)
list(APPEND MOENCH_EXECUTABLES moenchAnalog)
add_executable(moenchPhotonCounterHighZ moenchPhotonCounter.cpp ../tiffIO.cpp)
target_compile_definitions(moenchPhotonCounterHighZ PRIVATE NEWRECEIVER HIGHZ)
list(APPEND MOENCH_EXECUTABLES moenchPhotonCounterHighZ)
add_executable(moenchAnalogHighZ moenchPhotonCounter.cpp ../tiffIO.cpp)
target_compile_definitions(moenchAnalogHighZ PRIVATE NEWRECEIVER ANALOG HIGHZ)
list(APPEND MOENCH_EXECUTABLES moenchAnalogHighZ)
foreach(exe ${MOENCH_EXECUTABLES}) foreach(exe ${MOENCH_EXECUTABLES})
@ -56,8 +61,6 @@ foreach(exe ${MOENCH_EXECUTABLES})
../dataStructures ../dataStructures
../interpolations ../interpolations
../../slsReceiverSoftware/include/ ../../slsReceiverSoftware/include/
../../slsSupportLib/include/
${SLS_INTERNAL_RAPIDJSON_DIR}
) )
target_link_libraries(${exe} target_link_libraries(${exe}
@ -65,11 +68,10 @@ foreach(exe ${MOENCH_EXECUTABLES})
slsSupportStatic slsSupportStatic
${ZeroMQ_LIBRARIES} ${ZeroMQ_LIBRARIES}
pthread pthread
tiffio TIFF::TIFF
PRIVATE PRIVATE
slsProjectWarnings slsProjectWarnings
slsProjectOptions
) )
@ -81,6 +83,8 @@ foreach(exe ${MOENCH_EXECUTABLES})
endif() endif()
endforeach(exe ${MOENCH_EXECUTABLES}) endforeach(exe ${MOENCH_EXECUTABLES})
install(TARGETS ${MOENCH_EXECUTABLES} DESTINATION bin) install(TARGETS ${MOENCH_EXECUTABLES} DESTINATION bin)

View File

@ -0,0 +1,219 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
//#include "sls/ansi.h"
#include <iostream>
//#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
#ifdef REORDERED
#include "moench03T1ReorderedData.h"
#endif
// #include "interpolatingDetector.h"
//#include "etaInterpolationPosXY.h"
// #include "linearInterpolation.h"
// #include "noInterpolation.h"
#include "multiThreadedAnalogDetector.h"
#include "singlePhotonDetector.h"
//#include "interpolatingDetector.h"
#include <fstream>
#include <map>
#include <stdio.h>
#include <sys/stat.h>
#include <ctime>
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 = 1;
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!" << endl;
#endif
moench03T1ReceiverDataNew *decoder = new moench03T1ReceiverDataNew();
cout << "RECEIVER DATA WITH ONE HEADER!" << endl;
#endif
#ifdef CSAXS_FP
moench03T1ReceiverData *decoder = new moench03T1ReceiverData();
cout << "RECEIVER DATA WITH ALL HEADERS!" << endl;
#endif
#ifdef OLDDATA
moench03Ctb10GbT1Data *decoder = new moench03Ctb10GbT1Data();
cout << "OLD RECEIVER DATA!" << endl;
#endif
#ifdef REORDERED
moench03T1ReorderedData *decoder = new moench03T1ReorderedData();
cout << "REORDERED DATA!" << endl;
#endif
decoder->getDetectorSize(nx, ny);
cout << "nx " << nx << " ny " << ny << endl;
// moench03T1ZmqData *decoder=new moench03T1ZmqData();
singlePhotonDetector *filter =
new singlePhotonDetector(decoder, csize, nsigma, 1, 0, nped, 200);
// 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();
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; irun < runmax; irun++) {
sprintf(fn, fformat, irun);
sprintf(fname, "%s/%s.raw", indir, fn);
sprintf(outfname, "%s/%s.clust", outdir, fn);
sprintf(imgfname, "%s/%s.tiff", outdir, fn);
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 << "*"<<ifr++<<"*"<<ff<< endl;
// cout << ff << " " << np << endl;
// //push
// for (int ix=0; ix<400; ix++)
// for (int iy=0; iy<400; iy++) {
// if (decoder->getChannel(buff, ix, iy)<3000 ||
// decoder->getChannel(buff, ix, iy)>8000) {
// cout << ifr << " " << ff << " " << ix << " " << iy <<
// " " << decoder->getChannel(buff, ix, iy) << endl ;
// }
// }
mt->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;
}

View File

@ -47,6 +47,7 @@ int main(int argc, char *argv[]) {
#endif #endif
int iarg = 4; int iarg = 4;
char infname[10000]; char infname[10000];
char fname[10000];
char outfname[10000]; char outfname[10000];
#ifndef FF #ifndef FF
iarg = 4; iarg = 4;
@ -73,17 +74,18 @@ int main(int argc, char *argv[]) {
int etabins = 1000; // nsubpix*2*100; int etabins = 1000; // nsubpix*2*100;
double etamin = -1, etamax = 2; double etamin = -1, etamax = 2;
// double etamin=-0.1, etamax=1.1; // double etamin=-0.1, etamax=1.1;
// double eta3min = -2, eta3max = 2; double eta3min = -2, eta3max = 2;
int quad;
double sum, totquad; double sum, totquad;
double sDum[2][2]; double sDum[2][2];
double etax, etay; double etax, etay, int_x, int_y;
// double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y; double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y;
int ok;
int f0 = -1;
int ix, iy, isx, isy; int ix, iy, isx, isy;
int nframes = 0, lastframe = -1; int nframes = 0, lastframe = -1;
//double d_x, d_y, res = 5, xx, yy; double d_x, d_y, res = 5, xx, yy;
int nph = 0, totph = 0; int nph = 0, badph = 0, totph = 0;
//badph = 0,
FILE *f = NULL; FILE *f = NULL;
#ifdef DOUBLE_SPH #ifdef DOUBLE_SPH
@ -94,8 +96,7 @@ int main(int argc, char *argv[]) {
single_photon_hit cl(3, 3); single_photon_hit cl(3, 3);
#endif #endif
//int f0 = -1; int nSubPixels = nsubpix;
// int nSubPixels = nsubpix;
#ifndef NOINTERPOLATION #ifndef NOINTERPOLATION
eta2InterpolationPosXY *interp = eta2InterpolationPosXY *interp =
new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax);
@ -108,12 +109,7 @@ int main(int argc, char *argv[]) {
#endif #endif
#ifndef FF #ifndef FF
int quad;
#ifndef NOINTERPOLATION #ifndef NOINTERPOLATION
char fname[10000];
int ok;
double int_x, int_y;
int *img;
cout << "read ff " << argv[2] << endl; cout << "read ff " << argv[2] << endl;
sprintf(fname, "%s", argv[2]); sprintf(fname, "%s", argv[2]);
interp->readFlatField(fname); interp->readFlatField(fname);
@ -125,6 +121,7 @@ int main(int argc, char *argv[]) {
cout << "Will write eta file " << argv[2] << endl; cout << "Will write eta file " << argv[2] << endl;
#endif #endif
int *img;
float *totimg = new float[NC * NR * nsubpix * nsubpix]; float *totimg = new float[NC * NR * nsubpix * nsubpix];
for (ix = 0; ix < NC; ix++) { for (ix = 0; ix < NC; ix++) {
for (iy = 0; iy < NR; iy++) { for (iy = 0; iy < NR; iy++) {
@ -152,7 +149,7 @@ int main(int argc, char *argv[]) {
if (f) { if (f) {
cout << infname << endl; cout << infname << endl;
nframes = 0; nframes = 0;
//f0 = -1; f0 = -1;
while (cl.read(f)) { while (cl.read(f)) {
totph++; totph++;
@ -160,20 +157,13 @@ int main(int argc, char *argv[]) {
lastframe = cl.iframe; lastframe = cl.iframe;
// cout << cl.iframe << endl; // cout << cl.iframe << endl;
// f0=cl.iframe; // f0=cl.iframe;
// if (nframes == 0) if (nframes == 0)
// f0 = lastframe; f0 = lastframe;
nframes++; nframes++;
} }
// quad=interp->calcQuad(cl.get_cluster(), sum, totquad, sDum); // quad=interp->calcQuad(cl.get_cluster(), sum, totquad, sDum);
#ifndef FF
quad = interp->calcEta(cl.get_cluster(), etax, etay, sum, quad = interp->calcEta(cl.get_cluster(), etax, etay, sum,
totquad, sDum); totquad, sDum);
#endif
#ifdef FF
interp->calcEta(cl.get_cluster(), etax, etay, sum,
totquad, sDum);
#endif
if (sum > cmin && totquad / sum > 0.8 && totquad / sum < 1.2 && if (sum > cmin && totquad / sum > 0.8 && totquad / sum < 1.2 &&
sum < cmax) { sum < cmax) {
nph++; nph++;
@ -209,7 +199,7 @@ int main(int argc, char *argv[]) {
// if (cl.x>50) // if (cl.x>50)
// #endif // #endif
// if (etax!=0 && etay!=0 && etax!=1 && etay!=1) // if (etax!=0 && etay!=0 && etax!=1 && etay!=1)
interp->addToFlatFieldDistribution(etax, etay); interp->addToFlatField(etax, etay);
// if (etax==0 || etay==0) cout << cl.x << " " << cl.y << // if (etax==0 || etay==0) cout << cl.x << " " << cl.y <<
// endl; // endl;
@ -252,9 +242,9 @@ int main(int argc, char *argv[]) {
} }
} }
} }
// cout << "Read " << nframes << " frames (first frame: " << f0 cout << "Read " << nframes << " frames (first frame: " << f0
// << " last frame: " << lastframe << " delta:" << lastframe - f0 << " last frame: " << lastframe << " delta:" << lastframe - f0
// << ") nph=" << nph << endl; << ") nph=" << nph << endl;
interp->clearInterpolatedImage(); interp->clearInterpolatedImage();
#endif #endif

View File

@ -2,33 +2,43 @@
// Copyright (C) 2021 Contributors to the SLS Detector Package // Copyright (C) 2021 Contributors to the SLS Detector Package
//#include "sls/ansi.h" //#include "sls/ansi.h"
#include <iostream> #include <iostream>
#undef CORR #define CORR
#define C_GHOST 0.0004 #define C_GHOST 0.0004
#define CM_ROWS 50 #define CM_ROWS 50
#define RAWDATA //#define VERSION_V1
#ifndef MOENCH04 //#include "moench03T1ZmqData.h"
#ifdef NEWRECEIVER
#ifndef RECT #ifndef RECT
#include "moench03T1ReceiverDataNew.h" #include "moench03T1ReceiverDataNew.h"
#endif #endif
#endif
#ifdef RECT #ifdef RECT
#include "moench03T1ReceiverDataNewRect.h" #include "moench03T1ReceiverDataNewRect.h"
#endif #endif
#ifdef MOENCH04
#include "moench04CtbZmq10GbData.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 "multiThreadedCountingDetector.h" #include "multiThreadedCountingDetector.h"
//#include "multiThreadedAnalogDetector.h"
#include "moench03CommonMode.h" #include "moench03CommonMode.h"
#include "moench03GhostSummation.h" #include "moench03GhostSummation.h"
#include "singlePhotonDetector.h" #include "singlePhotonDetector.h"
//#include "interpolatingDetector.h"
#include <fstream> #include <fstream>
#include <map> #include <map>
@ -42,7 +52,7 @@ int main(int argc, char *argv[]) {
if (argc < 4) { if (argc < 4) {
cout << "Usage is " << argv[0] cout << "Usage is " << argv[0]
<< "indir outdir fname(no extension) [runmin] [runmax] [pedfile (raw or tiff)] [threshold] " << "indir outdir fname [runmin] [runmax] [pedfile] [threshold] "
"[nframes] [xmin xmax ymin ymax] [gainmap]" "[nframes] [xmin xmax ymin ymax] [gainmap]"
<< endl; << endl;
cout << "threshold <0 means analog; threshold=0 means cluster finder; " cout << "threshold <0 means analog; threshold=0 means cluster finder; "
@ -54,39 +64,55 @@ int main(int argc, char *argv[]) {
return 1; return 1;
} }
int p = 10000;
int fifosize = 1000; int fifosize = 1000;
int nthreads = 10; int nthreads = 10;
int nsubpix = 25;
int etabins = nsubpix * 10;
double etamin = -1, etamax = 2;
int csize = 3; int csize = 3;
int save = 1;
int nsigma = 5; int nsigma = 5;
int nped = 10000; int nped = 10000;
int ndark = 100;
int ok;
int iprog = 0;
int cf = 0; int cf = 0;
#ifdef NEWRECEIVER
#ifdef RECT #ifdef RECT
cout << "Should be rectangular but now it will crash! No data structure defined!" << endl; cout << "Should be rectangular!" << endl;
#endif #endif
#ifndef MOENCH04
moench03T1ReceiverDataNew *decoder = new moench03T1ReceiverDataNew(); moench03T1ReceiverDataNew *decoder = new moench03T1ReceiverDataNew();
cout << "MOENCH03!" << endl; cout << "RECEIVER DATA WITH ONE HEADER!" << endl;
#endif #endif
#ifdef MOENCH04 #ifdef CSAXS_FP
moench04CtbZmq10GbData *decoder = new moench04CtbZmq10GbData(); moench03T1ReceiverData *decoder = new moench03T1ReceiverData();
cout << "MOENCH04!" << endl; cout << "RECEIVER DATA WITH ALL HEADERS!" << endl;
#endif #endif
#ifdef OLDDATA
moench03Ctb10GbT1Data *decoder = new moench03Ctb10GbT1Data();
cout << "OLD RECEIVER DATA!" << endl;
#endif
int nx = 400, ny = 400; int nx = 400, ny = 400;
decoder->getDetectorSize(nx, ny); decoder->getDetectorSize(nx, ny);
#ifdef CORR
int ncol_cm = CM_ROWS; int ncol_cm = CM_ROWS;
double xt_ghost = C_GHOST; double xt_ghost = C_GHOST;
#endif
moench03CommonMode *cm = NULL; moench03CommonMode *cm = NULL;
moench03GhostSummation *gs; moench03GhostSummation *gs;
double *gainmap = NULL; double *gainmap = NULL;
//float *gm; float *gm;
int size = 327680; ////atoi(argv[3]);
int *image;
// int* image =new int[327680/sizeof(int)];
int ff, np; int ff, np;
// cout << " data size is " << dsize; // cout << " data size is " << dsize;
@ -143,6 +169,7 @@ int main(int argc, char *argv[]) {
char fname[10000]; char fname[10000];
char imgfname[10000]; char imgfname[10000];
char cfname[10000]; char cfname[10000];
char fn[10000];
std::time_t end_time; std::time_t end_time;
@ -159,6 +186,19 @@ int main(int argc, char *argv[]) {
cout << "Nframes is " << nframes << endl; cout << "Nframes is " << nframes << endl;
uint32_t nnx, nny; uint32_t nnx, nny;
double *gmap;
// if (gainfname) {
// gm=ReadFromTiff(gainfname, nny, nnx);
// if (gm && nnx==nx && nny==ny) {
// gmap=new double[nx*ny];
// for (int i=0; i<nx*ny; i++) {
// gmap[i]=gm[i];
// }
// delete gm;
// } else
// cout << "Could not open gain map " << gainfname << endl;
// }
#ifdef CORR #ifdef CORR
cout << "Applying common mode " << ncol_cm << endl; cout << "Applying common mode " << ncol_cm << endl;
@ -180,15 +220,21 @@ int main(int argc, char *argv[]) {
} else } else
thr = 0.15 * thr; thr = 0.15 * thr;
filter->newDataSet(); filter->newDataSet();
//int dsize = decoder->getDataSize(); int dsize = decoder->getDataSize();
char data[dsize];
//#ifndef ANALOG
if (thr > 0) { if (thr > 0) {
cout << "threshold is " << thr << endl; cout << "threshold is " << thr << endl;
//#ifndef ANALOG
filter->setThreshold(thr); filter->setThreshold(thr);
//#endif
cf = 0; cf = 0;
} else } else
cf = 1; cf = 1;
//#endif
filter->setROI(xmin, xmax, ymin, ymax); filter->setROI(xmin, xmax, ymin, ymax);
std::time(&end_time); std::time(&end_time);
@ -223,7 +269,7 @@ int main(int argc, char *argv[]) {
int ifr = 0; int ifr = 0;
double *ped=new double[nx * ny];//, *ped1; double ped[nx * ny], *ped1;
if (pedfile) { if (pedfile) {
@ -231,10 +277,10 @@ int main(int argc, char *argv[]) {
sprintf(imgfname, "%s/pedestals.tiff", outdir); sprintf(imgfname, "%s/pedestals.tiff", outdir);
if (string(pedfile).find(".tif") == std::string::npos) { if (string(pedfile).find(".tif") == std::string::npos) {
sprintf(fname, "%s", pedfile); sprintf(fname, "%s.raw", pedfile);
cout << fname << endl; cout << fname << endl;
std::time(&end_time); std::time(&end_time);
//cout << "aaa" << std::ctime(&end_time) << endl; cout << "aaa" << std::ctime(&end_time) << endl;
mt->setFrameMode(ePedestal); mt->setFrameMode(ePedestal);
// sprintf(fn,fformat,irun); // sprintf(fn,fformat,irun);
@ -264,12 +310,18 @@ int main(int argc, char *argv[]) {
<< " for reading " << endl; << " for reading " << endl;
} else { } else {
float *pp = ReadFromTiff(pedfile, nny, nnx); float *pp = ReadFromTiff(pedfile, nny, nnx);
if (pp && (int)nnx == nx && (int)nny == ny) { if (pp && nnx == nx && nny == ny) {
for (int i = 0; i < nx * ny; i++) { for (int i = 0; i < nx * ny; i++) {
ped[i] = pp[i]; ped[i] = pp[i];
} }
delete[] pp; delete[] pp;
mt->setPedestal(ped); mt->setPedestal(ped);
// ped1=mt->getPedestal();
// for (int i=0; i<nx*ny; i++) {
// cout << ped[i]<<"/"<<ped1[i] << " " ;
// }
cout << "Pedestal set from tiff file " << pedfile << endl; cout << "Pedestal set from tiff file " << pedfile << endl;
} else { } else {
cout << "Could not open pedestal tiff file " << pedfile cout << "Could not open pedestal tiff file " << pedfile
@ -290,11 +342,11 @@ int main(int argc, char *argv[]) {
cout << "DATA "; cout << "DATA ";
// sprintf(fn,fformat,irun); // sprintf(fn,fformat,irun);
sprintf(ffname, "%s/%s.raw", indir, fformat); sprintf(ffname, "%s/%s.raw", indir, fformat);
sprintf(fname, (const char*)ffname, irun); sprintf(fname, ffname, irun);
sprintf(ffname, "%s/%s.tiff", outdir, fformat); sprintf(ffname, "%s/%s.tiff", outdir, fformat);
sprintf(imgfname, (const char*)ffname, irun); sprintf(imgfname, ffname, irun);
sprintf(ffname, "%s/%s.clust", outdir, fformat); sprintf(ffname, "%s/%s.clust", outdir, fformat);
sprintf(cfname, (const char*)ffname, irun); sprintf(cfname, ffname, irun);
cout << fname << " "; cout << fname << " ";
cout << imgfname << endl; cout << imgfname << endl;
std::time(&end_time); std::time(&end_time);
@ -323,10 +375,13 @@ int main(int argc, char *argv[]) {
ifr = 0; ifr = 0;
while (decoder->readNextFrame(filebin, ff, np, buff)) { while (decoder->readNextFrame(filebin, ff, np, buff)) {
if (np == 40) { if (np == 40) {
// cout << "*"<<ifr++<<"*"<<ff<< endl;
// cout << ff << " " << np << endl;
// //push // //push
mt->pushData(buff); mt->pushData(buff);
// // //pop // // //pop
mt->nextThread(); mt->nextThread();
// // // cout << " " << (void*)buff;
mt->popFree(buff); mt->popFree(buff);
ifr++; ifr++;
@ -334,9 +389,15 @@ int main(int argc, char *argv[]) {
cout << ifr << " " << ff << endl; cout << ifr << " " << ff << endl;
if (nframes > 0) { if (nframes > 0) {
if (ifr % 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, sprintf(ffname, "%s/%s_f%05d.tiff", outdir, fformat,
ifile); ifile);
sprintf(imgfname, (const char*)ffname, irun); sprintf(imgfname, ffname, irun);
// cout << "Writing tiff to " << imgfname << " " <<
// thr1 << endl;
mt->writeImage(imgfname, thr1); mt->writeImage(imgfname, thr1);
mt->clearImage(); mt->clearImage();
ifile++; ifile++;
@ -348,16 +409,18 @@ int main(int argc, char *argv[]) {
} }
cout << "--" << endl; cout << "--" << endl;
filebin.close(); filebin.close();
// //close file
// //join threads
while (mt->isBusy()) { while (mt->isBusy()) {
; ;
} }
if (nframes >= 0) { if (nframes >= 0) {
if (nframes > 0) { if (nframes > 0) {
sprintf(ffname, "%s/%s_f%05d.tiff", outdir, fformat, ifile); sprintf(ffname, "%s/%s_f%05d.tiff", outdir, fformat, ifile);
sprintf(imgfname, (const char*)ffname, irun); sprintf(imgfname, ffname, irun);
} else { } else {
sprintf(ffname, "%s/%s.tiff", outdir, fformat); sprintf(ffname, "%s/%s.tiff", outdir, fformat);
sprintf(imgfname, (const char*)ffname, irun); sprintf(imgfname, ffname, irun);
} }
cout << "Writing tiff to " << imgfname << " " << thr1 << endl; cout << "Writing tiff to " << imgfname << " " << thr1 << endl;
mt->writeImage(imgfname, thr1); mt->writeImage(imgfname, thr1);

View File

@ -1,9 +1,9 @@
// SPDX-License-Identifier: LGPL-3.0-or-other // SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package // Copyright (C) 2021 Contributors to the SLS Detector Package
//#define WRITE_QUAD //#define WRITE_QUAD
//#define DEVELOPER #define DEVELOPER
#undef CORR #undef CORR
//#undef MOENCH04 #undef MOENCH04
#define C_GHOST 0.0004 #define C_GHOST 0.0004
@ -11,21 +11,21 @@
#include "sls/ZmqSocket.h" #include "sls/ZmqSocket.h"
#include "sls/sls_detector_defs.h" #include "sls/sls_detector_defs.h"
#ifndef RECT
#ifndef MOENCH04 #ifndef MOENCH04
//#ifndef RECT
#include "moench03T1ZmqDataNew.h" #include "moench03T1ZmqDataNew.h"
//#endif
//#ifdef RECT
//#include "moench03T1ZmqDataNewRect.h"
//#endif
#endif #endif
#ifdef MOENCH04 #ifdef MOENCH04
#include "moench04CtbZmq10GbData.h" #include "moench04CtbZmq10GbData.h"
#endif #endif
#endif
#ifdef RECT
#include "moench03T1ZmqDataNewRect.h"
#endif
#include "moench03CommonMode.h" #include "moench03CommonMode.h"
#include "moench03GhostSummation.h" #include "moench03GhostSummation.h"
#include "sls/tiffIO.h" #include "tiffIO.h"
#include <fstream> #include <fstream>
#include <iomanip> #include <iomanip>
#include <sstream> #include <sstream>
@ -156,7 +156,7 @@ int main(int argc, char *argv[]) {
int send_something = 0; int send_something = 0;
int maxSize = npx * npy * 2; // 32*2*8192;//5000;//atoi(argv[3]); int maxSize = npx * npy * 2; // 32*2*8192;//5000;//atoi(argv[3]);
int size = maxSize+sizeof(int); // 32*2*5000; int size = maxSize; // 32*2*5000;
// int multisize=size; // int multisize=size;
// int dataSize=size; // int dataSize=size;
@ -305,10 +305,10 @@ int main(int argc, char *argv[]) {
// header variables // header variables
uint64_t acqIndex = -1; uint64_t acqIndex = -1;
uint64_t frameIndex = -1; uint64_t frameIndex = -1;
// #ifdef MOENCH_BRANCH #ifdef MOENCH_BRANCH
// uint32_t subFrameIndex = -1; uint32_t subFrameIndex = -1;
// int *flippedData = 0; int *flippedData = 0;
// #endif #endif
uint64_t subframes = 0; uint64_t subframes = 0;
// uint64_t isubframe=0; // uint64_t isubframe=0;
@ -502,13 +502,13 @@ int main(int argc, char *argv[]) {
} }
#ifdef INTERP #ifdef INTERP
else if (fMode == eFlat) { else if (fMode == eFlat) {
int nbx, nby; int nb;
double emi = 0, ema = 1; double emi = 0, ema = 1;
int *ff = mt->getFlatField(nbx, nby, emi, ema); int *ff = mt->getFlatField(nb, emi, ema);
nnx = nbx; nnx = nb;
nny = nby; nny = nb;
dout = new int32_t[nbx * nby]; dout = new int32_t[nb * nb];
for (int ix = 0; ix < nbx * nby; ix++) { for (int ix = 0; ix < nb * nb; ix++) {
dout[ix] = ff[ix]; dout[ix] = ff[ix];
} }
} }

View File

@ -182,10 +182,10 @@ class threadedAnalogDetector {
interp->prepareInterpolation(ok); interp->prepareInterpolation(ok);
} }
virtual int *getFlatFieldDistribution() { virtual int *getFlatField() {
slsInterpolation *interp = (det)->getInterpolation(); slsInterpolation *interp = (det)->getInterpolation();
if (interp) if (interp)
return interp->getFlatFieldDistribution(); return interp->getFlatField();
else else
return NULL; return NULL;
} }
@ -208,19 +208,19 @@ class threadedAnalogDetector {
return NULL; return NULL;
} }
void *readFlatField(const char *imgname, double emin = 1, void *readFlatField(const char *imgname, int nb = -1, double emin = 1,
double emax = 0) { double emax = 0) {
slsInterpolation *interp = (det)->getInterpolation(); slsInterpolation *interp = (det)->getInterpolation();
if (interp) if (interp)
return interp->readFlatField(imgname, emin, emax); return interp->readFlatField(imgname, nb, emin, emax);
return NULL; return NULL;
} }
virtual int *getFlatField(int &nbx, int &nby, double &emi, double &ema) { virtual int *getFlatField(int &nb, double emi, double ema) {
slsInterpolation *interp = (det)->getInterpolation(); slsInterpolation *interp = (det)->getInterpolation();
int *ff = NULL; int *ff = NULL;
if (interp) { if (interp) {
ff = interp->getFlatField(nbx, nby, emi, ema); ff = interp->getFlatField(nb, emi, ema);
} }
return ff; return ff;
} }

View File

@ -25,10 +25,10 @@ class multiThreadedInterpolatingDetector
// } // }
} }
virtual int *getFlatFieldDistribution() { return (dets[0])->getFlatFieldDistribution(); } virtual int *getFlatField() { return (dets[0])->getFlatField(); }
virtual int *getFlatField(int &nbx, int &nby, double &emi, double &ema) { virtual int *getFlatField(int &nb, double emi, double ema) {
return (dets[0])->getFlatField(nbx, nby, emi, ema); return (dets[0])->getFlatField(nb, emi, ema);
} }
virtual int *setFlatField(int *h = NULL, int nb = -1, double emin = 1, virtual int *setFlatField(int *h = NULL, int nb = -1, double emin = 1,
@ -40,9 +40,9 @@ class multiThreadedInterpolatingDetector
return dets[0]->writeFlatField(imgname); return dets[0]->writeFlatField(imgname);
}; };
void *readFlatField(const char *imgname, double emin = 1, void *readFlatField(const char *imgname, int nb = -1, double emin = 1,
double emax = 0) { double emax = 0) {
return (dets[0])->readFlatField(imgname, emin, emax); return (dets[0])->readFlatField(imgname, nb, emin, emax);
}; };
/* virtual int setNSubPixels(int ns) { return /* virtual int setNSubPixels(int ns) { return

View File

@ -429,15 +429,10 @@ class singlePhotonDetector : public analogDetector<uint16_t> {
for (ic = -(clusterSize / 2); ic < (clusterSize / 2) + 1; for (ic = -(clusterSize / 2); ic < (clusterSize / 2) + 1;
ic++) { ic++) {
if ((iy + ir) >= 0 && (iy + ir) < ny && if ((iy + ir) >= iy && (iy + ir) < ny &&
(ix + ic) >= 0 && (ix + ic) < nx) { (ix + ic) >= ix && (ix + ic) < nx) {
if ((iy + ir) >= iy && (ix + ic) >= ix ) {
val[(iy + ir) * nx + ix + ic] = val[(iy + ir) * nx + ix + ic] =
subtractPedestal(data, ix + ic, iy + ir, cm); subtractPedestal(data, ix + ic, iy + ir, cm);
}
v = &(val[(iy + ir) * nx + ix + ic]); v = &(val[(iy + ir) * nx + ix + ic]);
tot += *v; tot += *v;
if (ir <= 0 && ic <= 0) if (ir <= 0 && ic <= 0)
@ -448,9 +443,9 @@ class singlePhotonDetector : public analogDetector<uint16_t> {
tl += *v; tl += *v;
if (ir >= 0 && ic >= 0) if (ir >= 0 && ic >= 0)
tr += *v; tr += *v;
if (*v > max) //{ if (*v > max) {
max = *v; max = *v;
//} }
} }
} }
} }
@ -518,19 +513,12 @@ class singlePhotonDetector : public analogDetector<uint16_t> {
for (ic = -(clusterSize / 2); for (ic = -(clusterSize / 2);
ic < (clusterSize / 2) + 1; ic++) { ic < (clusterSize / 2) + 1; ic++) {
if ((iy + ir) >= 0 && (iy + ir) < ny && if ((iy + ir) >= 0 && (iy + ir) < ny &&
(ix + ic) >= 0 && (ix + ic) < nx) { (ix + ic) >= 0 && (ix + ic) < nx)
(clusters + nph) (clusters + nph)
->set_data(val[(iy + ir) * nx + ix + ic], ->set_data(val[(iy + ir) * nx + ix + ic],
ic, ir); ic, ir);
if (val[(iy + ir) * nx + ix + ic]>max)
good=0;
} }
} }
}
if (good==0) {
(clusters + nph)->print();
cout << max << " " << val[iy * nx + ix] << endl;
}
good = 1; good = 1;
if (eMin > 0 && tot < eMin) if (eMin > 0 && tot < eMin)
good = 0; good = 0;

View File

@ -216,18 +216,14 @@ class single_photon_hit {
// int ix, iy; // int ix, iy;
printf("***************\n");
printf("** %d %d **\n",x,y);
for (int iy = 0; iy < dy; iy++) { for (int iy = 0; iy < dy; iy++) {
for (int ix = 0; ix < dx; ix++) { for (int ix = 0; ix < dx; ix++) {
printf("%d \t", data[ix + iy * dx]); printf("%d \t", data[ix + iy * dx]);
} }
printf("\n"); printf("\n");
} }
printf("***************\n");
} }
/** /**
assign the value to the element of the cluster matrix, with relative 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 coordinates where the center of the cluster is (0,0) \param v value to be

View File

@ -1,12 +1,26 @@
// SPDX-License-Identifier: LGPL-3.0-or-other // SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package // Copyright (C) 2021 Contributors to the SLS Detector Package
#ifndef MY_TIFF_IO_H
#include "sls/tiffIO.h" #include "tiffIO.h"
#endif
#include <iostream> #include <iostream>
#include <tiffio.h> 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) { void *WriteToTiff(float *imgData, const char *imgname, int nrow, int ncol) {
constexpr uint32_t sampleperpixel = 1; int sampleperpixel = 1;
// unsigned char * buff=NULL;
// tsize_t linebytes;
// cout << "--" <<endl;
TIFF *tif = TIFFOpen(imgname, "w"); TIFF *tif = TIFFOpen(imgname, "w");
if (tif) { if (tif) {
TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, ncol); TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, ncol);
@ -17,32 +31,50 @@ void *WriteToTiff(float *imgData, const char *imgname, int nrow, int ncol) {
TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
// linebytes = sampleperpixel*ncol;
TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,
TIFFDefaultStripSize(tif, ncol * sampleperpixel)); TIFFDefaultStripSize(tif, ncol * sampleperpixel));
for (int irow = 0; irow < nrow; irow++) { for (int irow = 0; irow < nrow; irow++) {
TIFFWriteScanline(tif, &imgData[irow * ncol], irow, 0); TIFFWriteScanline(tif, &imgData[irow * ncol], irow, 0);
} }
TIFFClose(tif); TIFFClose(tif);
} else { } else
std::cout << "could not open file " << imgname << " for writing\n"; cout << "could not open file " << imgname << " for writing " << endl;
}
return nullptr; return NULL;
} };
float *ReadFromTiff(const char *imgname, uint32_t &nrow, uint32_t &ncol) { float *ReadFromTiff(const char *imgname, uint32_t &nrow, uint32_t &ncol) {
// unsigned char * buff=NULL;
TIFF *tif = TIFFOpen(imgname, "r"); TIFF *tif = TIFFOpen(imgname, "r");
if (tif) { if (tif) {
uint32_t bps;
uint32_t sampleperpixel = 1;
// tsize_t linebytes;
uint32_t imagelength;
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &ncol); TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &ncol);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &nrow); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &nrow);
TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, sampleperpixel);
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imagelength);
float *imgData = new float[ncol * nrow]; float *imgData = new float[ncol * nrow];
for (uint32_t irow = 0; irow < nrow; ++irow) { // linebytes = sampleperpixel*ncol;
// TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif,
// ncol*sampleperpixel));
for (uint32_t irow = 0; irow < nrow; irow++) {
// tiffreadscanline(tif, buf, row);
TIFFReadScanline(tif, &imgData[irow * ncol], irow); TIFFReadScanline(tif, &imgData[irow * ncol], irow);
} }
TIFFClose(tif); TIFFClose(tif);
return imgData; return imgData;
} else { } else
std::cout << "could not open file " << imgname << " for reading\n"; cout << "could not open file " << imgname << " for reading " << endl;
return nullptr; return NULL;
} };
}

View File

@ -0,0 +1,35 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#ifndef MY_TIFF_IO_H
#define MY_TIFF_IO_H
#include <fstream>
#include <iomanip>
#include <sstream>
#include <stdio.h>
#include <string>
#include <vector>
/*****************************************************************************/
//
// 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_t &nrow, uint32_t &ncol);
#endif

View File

@ -1,14 +0,0 @@
find_package(TIFF REQUIRED)
add_library(tiffio STATIC src/tiffIO.cpp)
target_include_directories(tiffio PUBLIC include/)
target_link_libraries(tiffio
PUBLIC
TIFF::TIFF
PRIVATE
slsProjectWarnings
slsProjectOptions
)
if(SLS_USE_TESTS)
add_subdirectory(tests)
endif()

View File

@ -1,16 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#include <cstdint>
//Write 32bit float data to tiff file
//Always returns nullptr, prints message on failure
void *WriteToTiff(float *imgData, const char *imgname, int nrow, int ncol);
//Read 32bit float data from tiff file, returns pointer to data and sets
//image dimensions in the out parameters nrow, ncol.
//Returns nullptr on failure
//The caller is responsible to deallocate the memory that the returned
//pointer points to.
float *ReadFromTiff(const char *imgname, uint32_t &nrow, uint32_t &ncol);

View File

@ -1,5 +0,0 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
target_sources(tests PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/test-tiffio.cpp
)

View File

@ -1,54 +0,0 @@
#include "catch.hpp"
#include "sls/tiffIO.h"
#include <cstdio>
#include <ftw.h>
#include <iostream>
#include <vector>
/* Call-back to the 'remove()' function called by nftw() */
static int remove_callback(const char *pathname,
__attribute__((unused)) const struct stat *sbuf,
__attribute__((unused)) int type,
__attribute__((unused)) struct FTW *ftwb) {
return remove(pathname);
}
TEST_CASE("Write and read back data from tiff file") {
std::vector<float> data{1, 2, 3, 4, 5, 6, 7, 8, 9};
/* Create the temporary directory */
char tmp[] = "/tmp/tmpdir.XXXXXX";
char *tmp_dirname = mkdtemp(tmp);
if (tmp_dirname == NULL) {
perror("tempdir: error: Could not create tmp directory");
CHECK(false);
}
std::string fname = std::string(tmp_dirname) + std::string("/test.tif");
std::cout << "Writing to: " << fname<< '\n';
WriteToTiff(data.data(), fname.c_str(), 3, 3);
//Readback
uint32_t nrow, ncol;
float* ptr = ReadFromTiff(fname.c_str(), nrow, ncol);
CHECK(nrow == 3);
CHECK(ncol == 3);
uint32_t size = nrow*ncol;
for (uint32_t i = 0; i!=size; ++i){
CHECK(data[i] == ptr[i]);
}
delete[] ptr;
/* Delete the temporary directory */
if (nftw(tmp_dirname, remove_callback, FOPEN_MAX,
FTW_DEPTH | FTW_MOUNT | FTW_PHYS) == -1) {
perror("tempdir: error: ");
exit(EXIT_FAILURE);
}
}

View File

@ -97,11 +97,6 @@
<string>65535</string> <string>65535</string>
</property> </property>
</item> </item>
<item>
<property name="text">
<string>4095</string>
</property>
</item>
<item> <item>
<property name="text"> <property name="text">
<string>255</string> <string>255</string>

View File

@ -91,10 +91,8 @@ class qDrawPlot : public QWidget, private Ui::PlotObject {
void Update2dPlot(); void Update2dPlot();
void Update1dXYRange(); void Update1dXYRange();
void Update2dXYRange(); void Update2dXYRange();
void rearrangeGotthard25data(double *data);
static const int NUM_PEDESTAL_FRAMES = 20; static const int NUM_PEDESTAL_FRAMES = 20;
static const int NUM_GOTTHARD25_CHANS = 1280;
sls::Detector *det; sls::Detector *det;
slsDetectorDefs::detectorType detType; slsDetectorDefs::detectorType detType;
@ -166,5 +164,4 @@ class qDrawPlot : public QWidget, private Ui::PlotObject {
uint32_t pixelMask{0}; uint32_t pixelMask{0};
uint32_t gainMask{0}; uint32_t gainMask{0};
int gainOffset{0}; int gainOffset{0};
bool gotthard25;
}; };

View File

@ -69,11 +69,5 @@ class qTabSettings : public QWidget, private Ui::TabSettingsObject {
enum { DYNAMIC, FORCE_SWITCH_G1, FORCE_SWITCH_G2, FIX_G1, FIX_G2, FIX_G0 }; enum { DYNAMIC, FORCE_SWITCH_G1, FORCE_SWITCH_G2, FIX_G1, FIX_G2, FIX_G0 };
bool isVisibleFixG0{false}; bool isVisibleFixG0{false};
enum { enum { DYNAMICRANGE_32, DYNAMICRANGE_16, DYNAMICRANGE_8, DYNAMICRANGE_4 };
DYNAMICRANGE_32,
DYNAMICRANGE_16,
DYNAMICRANGE_12,
DYNAMICRANGE_8,
DYNAMICRANGE_4
};
}; };

View File

@ -80,10 +80,6 @@ void qDrawPlot::SetupWidgetWindow() {
fileSaveName = "Image"; fileSaveName = "Image";
} }
gotthard25 = ((detType == slsDetectorDefs::GOTTHARD2 ||
detType == slsDetectorDefs::GOTTHARD) &&
det->size() == 2);
SetupPlots(); SetupPlots();
SetDataCallBack(true); SetDataCallBack(true);
det->registerAcquisitionFinishedCallback(&(GetAcquisitionFinishedCallBack), det->registerAcquisitionFinishedCallback(&(GetAcquisitionFinishedCallBack),
@ -811,11 +807,6 @@ void qDrawPlot::GetData(detectorData *data, uint64_t frameIndex,
isGainDataExtracted = false; isGainDataExtracted = false;
} }
// gotthard25um rearranging
if (gotthard25) {
rearrangeGotthard25data(rawData);
}
// title and frame index titles // title and frame index titles
plotTitle = plotTitle =
plotTitlePrefix + QString(data->fileName.c_str()).section('/', -1); plotTitlePrefix + QString(data->fileName.c_str()).section('/', -1);
@ -1073,8 +1064,6 @@ void qDrawPlot::toDoublePixelData(double *dest, char *source, int size,
// mythen3 / gotthard2 debugging // mythen3 / gotthard2 debugging
int discardBits = numDiscardBits; int discardBits = numDiscardBits;
uint16_t temp = 0;
uint8_t *src = (uint8_t *)source;
switch (dr) { switch (dr) {
case 4: case 4:
@ -1094,19 +1083,6 @@ void qDrawPlot::toDoublePixelData(double *dest, char *source, int size,
} }
break; break;
case 12:
for (ichan = 0; ichan < size; ++ichan) {
temp = (*src++ & 0xFF);
temp |= ((*src & 0xF) << 8u);
dest[ichan] = (double)temp;
++ichan;
temp = ((*src++ & 0xF0) >> 4u);
temp |= ((*src++ & 0xFF) << 4u);
dest[ichan] = (double)temp;
}
break;
case 16: case 16:
if (detType == slsDetectorDefs::JUNGFRAU || if (detType == slsDetectorDefs::JUNGFRAU ||
detType == slsDetectorDefs::GOTTHARD2) { detType == slsDetectorDefs::GOTTHARD2) {
@ -1154,18 +1130,6 @@ void qDrawPlot::toDoublePixelData(double *dest, char *source, int size,
} }
} }
void qDrawPlot::rearrangeGotthard25data(double *data) {
const int nChans = NUM_GOTTHARD25_CHANS;
double temp[nChans * 2] = {0.0};
for (int i = 0; i != nChans; ++i) {
// master module
temp[i * 2] = data[i];
// slave module
temp[i * 2 + 1] = data[nChans + i];
}
memcpy(data, temp, nChans * 2 * sizeof(double));
}
void qDrawPlot::UpdatePlot() { void qDrawPlot::UpdatePlot() {
std::lock_guard<std::mutex> lock(mPlots); std::lock_guard<std::mutex> lock(mPlots);
LOG(logDEBUG) << "Update Plot"; LOG(logDEBUG) << "Update Plot";

View File

@ -60,19 +60,13 @@ void qTabSettings::SetupWidgetWindow() {
QStandardItemModel *model = QStandardItemModel *model =
qobject_cast<QStandardItemModel *>(comboDynamicRange->model()); qobject_cast<QStandardItemModel *>(comboDynamicRange->model());
if (model) { if (model) {
QModelIndex index;
QStandardItem *item; QStandardItem *item;
int dr = DYNAMICRANGE_4; index =
for (int i = 0; i != 2; ++i) { model->index(DYNAMICRANGE_4, comboDynamicRange->modelColumn(),
// disable dr 4
QModelIndex index =
model->index(dr, comboDynamicRange->modelColumn(),
comboDynamicRange->rootModelIndex()); comboDynamicRange->rootModelIndex());
item = model->itemFromIndex(index); item = model->itemFromIndex(index);
item->setEnabled(false); item->setEnabled(false);
// disable dr 12
dr = DYNAMICRANGE_12;
}
} }
} else if (detType == slsDetectorDefs::EIGER) { } else if (detType == slsDetectorDefs::EIGER) {
lblDynamicRange->setEnabled(true); lblDynamicRange->setEnabled(true);
@ -311,9 +305,6 @@ void qTabSettings::GetDynamicRange() {
case 16: case 16:
comboDynamicRange->setCurrentIndex(DYNAMICRANGE_16); comboDynamicRange->setCurrentIndex(DYNAMICRANGE_16);
break; break;
case 12:
comboDynamicRange->setCurrentIndex(DYNAMICRANGE_12);
break;
case 8: case 8:
comboDynamicRange->setCurrentIndex(DYNAMICRANGE_8); comboDynamicRange->setCurrentIndex(DYNAMICRANGE_8);
break; break;
@ -342,9 +333,6 @@ void qTabSettings::SetDynamicRange(int index) {
case DYNAMICRANGE_16: case DYNAMICRANGE_16:
det->setDynamicRange(16); det->setDynamicRange(16);
break; break;
case DYNAMICRANGE_12:
det->setDynamicRange(12);
break;
case DYNAMICRANGE_8: case DYNAMICRANGE_8:
det->setDynamicRange(8); det->setDynamicRange(8);
break; break;

View File

@ -165,9 +165,11 @@
#define PATTERN_OUT_LSB_REG (0x20 << MEM_MAP_SHIFT) #define PATTERN_OUT_LSB_REG (0x20 << MEM_MAP_SHIFT)
#define PATTERN_OUT_MSB_REG (0x21 << MEM_MAP_SHIFT) #define PATTERN_OUT_MSB_REG (0x21 << MEM_MAP_SHIFT)
/* Frame number of next acquisition register (64 bit register) */ /* Frames From Start 64 bit RO register TODO */
#define NEXT_FRAME_NUMB_LOCAL_LSB_REG (0x22 << MEM_MAP_SHIFT) //#define FRAMES_FROM_START_LSB_REG (0x22 << MEM_MAP_SHIFT) // Not
#define NEXT_FRAME_NUMB_LOCAL_MSB_REG (0x23 << MEM_MAP_SHIFT) // 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 */ /* 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_LSB_REG (0x24 << MEM_MAP_SHIFT)

View File

@ -45,6 +45,7 @@ char initErrorMessage[MAX_STR_LENGTH];
#ifdef VIRTUAL #ifdef VIRTUAL
pthread_t pthread_virtual_tid; pthread_t pthread_virtual_tid;
int64_t virtual_currentFrameNumber = 2;
#endif #endif
// 1g readout // 1g readout
@ -433,22 +434,17 @@ void initControlServer() {
} }
void initStopServer() { void initStopServer() {
if (!updateFlag && initError == OK) {
usleep(CTRL_SRVR_INIT_TIME_US); usleep(CTRL_SRVR_INIT_TIME_US);
if (mapCSP0() == FAIL) { if (mapCSP0() == FAIL) {
initError = FAIL; LOG(logERROR,
strcpy(initErrorMessage, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"));
"Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); exit(EXIT_FAILURE);
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
return;
} }
#ifdef VIRTUAL #ifdef VIRTUAL
sharedMemory_setStop(0); sharedMemory_setStop(0);
#endif #endif
} }
initCheckDone = 1;
}
/* set up detector */ /* set up detector */
@ -585,7 +581,6 @@ void setupDetector() {
LOG(logERROR, ("%s\n\n", initErrorMessage)); LOG(logERROR, ("%s\n\n", initErrorMessage));
initError = FAIL; initError = FAIL;
} }
setNextFrameNumber(DEFAULT_STARTING_FRAME_NUMBER);
} }
int updateDatabytesandAllocateRAM() { int updateDatabytesandAllocateRAM() {
@ -707,16 +702,8 @@ void resetPeripheral() {
} }
/* set parameters - dr, adcenablemask */ /* set parameters - dr, adcenablemask */
int setDynamicRange(int dr) {
if (dr == 16)
return OK;
return FAIL;
}
int getDynamicRange(int *retval) { int setDynamicRange(int dr) { return DYNAMIC_RANGE; }
*retval = DYNAMIC_RANGE;
return OK;
}
int setADCEnableMask(uint32_t mask) { int setADCEnableMask(uint32_t mask) {
if (mask == 0u) { if (mask == 0u) {
@ -911,24 +898,6 @@ int getReadoutMode() {
} }
/* parameters - timer */ /* parameters - timer */
int setNextFrameNumber(uint64_t value) {
LOG(logINFO,
("Setting next frame number: %llu\n", (long long unsigned int)value));
setU64BitReg(value, NEXT_FRAME_NUMB_LOCAL_LSB_REG,
NEXT_FRAME_NUMB_LOCAL_MSB_REG);
#ifndef VIRTUAL
// for 1g udp interface
setUDPFrameNumber(value);
#endif
return OK;
}
int getNextFrameNumber(uint64_t *retval) {
*retval = getU64BitReg(NEXT_FRAME_NUMB_LOCAL_LSB_REG,
NEXT_FRAME_NUMB_LOCAL_MSB_REG);
return OK;
}
void setNumFrames(int64_t val) { void setNumFrames(int64_t val) {
if (val > 0) { if (val > 0) {
LOG(logINFO, ("Setting number of frames %lld\n", (long long int)val)); LOG(logINFO, ("Setting number of frames %lld\n", (long long int)val));
@ -1523,8 +1492,6 @@ enum timingMode getTiming() {
/* configure mac */ /* configure mac */
int getNumberofUDPInterfaces() { return 1; }
void calcChecksum(udp_header *udp) { void calcChecksum(udp_header *udp) {
int count = IP_HEADER_SIZE; int count = IP_HEADER_SIZE;
long int sum = 0; long int sum = 0;
@ -2031,14 +1998,11 @@ void *start_timer(void *arg) {
} }
// Send data // Send data
uint64_t frameNr = 0;
getNextFrameNumber(&frameNr);
// loop over number of frames // loop over number of frames
for (int iframes = 0; iframes != numFrames; ++iframes) { for (int frameNr = 0; frameNr != numFrames; ++frameNr) {
// check if manual stop // check if manual stop
if (sharedMemory_getStop() == 1) { if (sharedMemory_getStop() == 1) {
setNextFrameNumber(frameNr + iframes + 1);
break; break;
} }
@ -2057,11 +2021,11 @@ void *start_timer(void *arg) {
sls_detector_header *header = (sls_detector_header *)(packetData); sls_detector_header *header = (sls_detector_header *)(packetData);
header->detType = (uint16_t)myDetectorType; header->detType = (uint16_t)myDetectorType;
header->version = SLS_DETECTOR_HEADER_VERSION - 1; header->version = SLS_DETECTOR_HEADER_VERSION - 1;
header->frameNumber = frameNr + iframes; header->frameNumber = virtual_currentFrameNumber;
header->packetNumber = i; header->packetNumber = i;
header->modId = 0; header->modId = 0;
header->row = detPos[Y]; header->row = detPos[X];
header->column = detPos[X]; header->column = detPos[Y];
// fill data // fill data
memcpy(packetData + sizeof(sls_detector_header), memcpy(packetData + sizeof(sls_detector_header),
@ -2070,18 +2034,19 @@ void *start_timer(void *arg) {
sendUDPPacket(0, 0, packetData, packetSize); sendUDPPacket(0, 0, packetData, packetSize);
} }
LOG(logINFO, ("Sent frame: %d [%lld]\n", iframes, frameNr + iframes)); LOG(logINFO, ("Sent frame: %d [%lld]\n", frameNr,
(long long unsigned int)virtual_currentFrameNumber));
clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_REALTIME, &end);
int64_t timeNs = int64_t timeNs =
((end.tv_sec - begin.tv_sec) * 1E9 + (end.tv_nsec - begin.tv_nsec)); ((end.tv_sec - begin.tv_sec) * 1E9 + (end.tv_nsec - begin.tv_nsec));
// sleep for (period - exptime) // sleep for (period - exptime)
if (iframes < numFrames) { // if there is a next frame if (frameNr < numFrames) { // if there is a next frame
if (periodNs > timeNs) { if (periodNs > timeNs) {
usleep((periodNs - timeNs) / 1000); usleep((periodNs - timeNs) / 1000);
} }
} }
setNextFrameNumber(frameNr + numFrames); ++virtual_currentFrameNumber;
} }
closeUDPSocket(0); closeUDPSocket(0);

View File

@ -109,7 +109,6 @@ enum CLKINDEX { RUN_CLK, ADC_CLK, SYNC_CLK, DBIT_CLK, NUM_CLOCKS };
/** Default Parameters */ /** Default Parameters */
#define DEFAULT_DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL) #define DEFAULT_DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL)
#define DEFAULT_STARTING_FRAME_NUMBER (1)
#define DEFAULT_NUM_SAMPLES (1) #define DEFAULT_NUM_SAMPLES (1)
#define DEFAULT_NUM_FRAMES (1) #define DEFAULT_NUM_FRAMES (1)
#define DEFAULT_EXPTIME (0) #define DEFAULT_EXPTIME (0)
@ -125,8 +124,6 @@ enum CLKINDEX { RUN_CLK, ADC_CLK, SYNC_CLK, DBIT_CLK, NUM_CLOCKS };
#define DEFAULT_SYNC_CLK (40) // 20 #define DEFAULT_SYNC_CLK (40) // 20
#define DEFAULT_DBIT_CLK (200) #define DEFAULT_DBIT_CLK (200)
#define UDP_HEADER_MAX_FRAME_VALUE (0xFFFFFFFFFFFF)
#define HIGHVOLTAGE_MIN (60) #define HIGHVOLTAGE_MIN (60)
#define HIGHVOLTAGE_MAX (200) // min dac val #define HIGHVOLTAGE_MAX (200) // min dac val
#define DAC_MIN_MV (0) #define DAC_MIN_MV (0)

View File

@ -177,7 +177,7 @@ void Beb_AdjustIPChecksum(struct udp_header_type *ip) {
ip->ip_header_checksum[1] = ip_checksum & 0xff; ip->ip_header_checksum[1] = ip_checksum & 0xff;
} }
int Beb_GetModuleConfiguration(int *master, int *top, int *normal) { void Beb_GetModuleConfiguration(int *master, int *top, int *normal) {
*top = 0; *top = 0;
*master = 0; *master = 0;
// mapping new memory to read master top module configuration // mapping new memory to read master top module configuration
@ -187,7 +187,6 @@ int Beb_GetModuleConfiguration(int *master, int *top, int *normal) {
int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR); int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR);
if (fd < 0) { if (fd < 0) {
LOG(logERROR, ("Module Configuration FAIL\n")); LOG(logERROR, ("Module Configuration FAIL\n"));
return FAIL;
} else { } else {
// read data // read data
ret = Beb_Read32(csp0base, BEB_CONFIG_RD_OFST); ret = Beb_Read32(csp0base, BEB_CONFIG_RD_OFST);
@ -203,7 +202,6 @@ int Beb_GetModuleConfiguration(int *master, int *top, int *normal) {
// close file pointer // close file pointer
Beb_close(fd, csp0base); Beb_close(fd, csp0base);
} }
return OK;
} }
int Beb_IsTransmitting(int *retval, int tengiga, int waitForDelay) { int Beb_IsTransmitting(int *retval, int tengiga, int waitForDelay) {
@ -494,11 +492,6 @@ int Beb_SetDataStream(enum portPosition port, int enable) {
u_int32_t reg = XPAR_GPIO_P15_STREAMING_REG; u_int32_t reg = XPAR_GPIO_P15_STREAMING_REG;
u_int32_t mask = (port == LEFT ? XPAR_GPIO_LFT_STRM_DSBL_MSK u_int32_t mask = (port == LEFT ? XPAR_GPIO_LFT_STRM_DSBL_MSK
: XPAR_GPIO_RGHT_STRM_DSBL_MSK); : XPAR_GPIO_RGHT_STRM_DSBL_MSK);
// invert left/right if bottom
if (!Beb_top) {
mask = (port == LEFT ? XPAR_GPIO_RGHT_STRM_DSBL_MSK
: XPAR_GPIO_LFT_STRM_DSBL_MSK);
}
u_int32_t value = Beb_Read32(csp0base, reg); u_int32_t value = Beb_Read32(csp0base, reg);
// disabling in firmware // disabling in firmware
@ -536,11 +529,6 @@ int Beb_GetDataStream(enum portPosition port, int *retval) {
u_int32_t reg = XPAR_GPIO_P15_STREAMING_REG; u_int32_t reg = XPAR_GPIO_P15_STREAMING_REG;
u_int32_t mask = (port == LEFT ? XPAR_GPIO_LFT_STRM_DSBL_MSK u_int32_t mask = (port == LEFT ? XPAR_GPIO_LFT_STRM_DSBL_MSK
: XPAR_GPIO_RGHT_STRM_DSBL_MSK); : XPAR_GPIO_RGHT_STRM_DSBL_MSK);
// invert left/right if bottom
if (!Beb_top) {
mask = (port == LEFT ? XPAR_GPIO_RGHT_STRM_DSBL_MSK
: XPAR_GPIO_LFT_STRM_DSBL_MSK);
}
u_int32_t value = Beb_Read32(csp0base, reg); u_int32_t value = Beb_Read32(csp0base, reg);
// disabling in firmware // disabling in firmware
@ -694,10 +682,6 @@ int Beb_GetTransmissionDelayLeft() {
return Beb_deactivated_transmission_delay_left; return Beb_deactivated_transmission_delay_left;
} }
u_int32_t offset = TXM_DELAY_LEFT_OFFSET; u_int32_t offset = TXM_DELAY_LEFT_OFFSET;
// invert left/right if bottom
if (!Beb_top) {
offset = TXM_DELAY_RIGHT_OFFSET;
}
u_int32_t *csp0base = 0; u_int32_t *csp0base = 0;
int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR); int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR);
if (fd <= 0) { if (fd <= 0) {
@ -722,10 +706,6 @@ int Beb_SetTransmissionDelayLeft(int value) {
return 1; return 1;
} }
u_int32_t offset = TXM_DELAY_LEFT_OFFSET; u_int32_t offset = TXM_DELAY_LEFT_OFFSET;
// invert left/right if bottom
if (!Beb_top) {
offset = TXM_DELAY_RIGHT_OFFSET;
}
u_int32_t *csp0base = 0; u_int32_t *csp0base = 0;
int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR); int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR);
if (fd <= 0) { if (fd <= 0) {
@ -746,10 +726,6 @@ int Beb_GetTransmissionDelayRight() {
} }
u_int32_t offset = TXM_DELAY_RIGHT_OFFSET; u_int32_t offset = TXM_DELAY_RIGHT_OFFSET;
// invert left/right if bottom
if (!Beb_top) {
offset = TXM_DELAY_LEFT_OFFSET;
}
u_int32_t *csp0base = 0; u_int32_t *csp0base = 0;
int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR); int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR);
if (fd <= 0) { if (fd <= 0) {
@ -774,10 +750,6 @@ int Beb_SetTransmissionDelayRight(int value) {
return 1; return 1;
} }
u_int32_t offset = TXM_DELAY_RIGHT_OFFSET; u_int32_t offset = TXM_DELAY_RIGHT_OFFSET;
// invert left/right if bottom
if (!Beb_top) {
offset = TXM_DELAY_LEFT_OFFSET;
}
u_int32_t *csp0base = 0; u_int32_t *csp0base = 0;
int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR); int fd = Beb_open(&csp0base, XPAR_PLB_GPIO_SYS_BASEADDR);
if (fd <= 0) { if (fd <= 0) {
@ -864,17 +836,11 @@ void Beb_ResetFrameNumber() {
} }
int Beb_SetUpTransferParameters(short the_bit_mode) { int Beb_SetUpTransferParameters(short the_bit_mode) {
switch (the_bit_mode) { if (the_bit_mode != 4 && the_bit_mode != 8 && the_bit_mode != 16 &&
case 4: the_bit_mode != 32)
case 8: return 0;
case 12:
case 16:
case 32:
Beb_bit_mode = the_bit_mode; Beb_bit_mode = the_bit_mode;
return 1; return 1;
default:
return 0;
}
} }
int Beb_StopAcquisition() { int Beb_StopAcquisition() {
@ -1095,19 +1061,19 @@ int *Beb_GetDetectorPosition() { return Beb_positions; }
int Beb_SetDetectorPosition(int pos[]) { int Beb_SetDetectorPosition(int pos[]) {
if (!Beb_activated) if (!Beb_activated)
return OK; return OK;
LOG(logINFO, ("Setting Position: (%d, %d)\n", pos[X], pos[Y])); LOG(logINFO, ("Got Position values %d %d...\n", pos[0], pos[1]));
// save positions // save positions
Beb_positions[Y] = pos[Y]; Beb_positions[0] = pos[0];
Beb_positions[X] = pos[X]; Beb_positions[1] = pos[1];
// get left and right // get left and right
int posLeft[2] = {Beb_top ? pos[X] : pos[X] + 1, pos[Y]}; int posLeft[2] = {pos[0], Beb_top ? pos[1] : pos[1] + 1};
int posRight[2] = {Beb_top ? pos[X] + 1 : pos[X], pos[Y]}; int posRight[2] = {pos[0], Beb_top ? pos[1] + 1 : pos[1]};
if (Beb_quadEnable) { if (Beb_quadEnable) {
posRight[Y] = 1; // right is next row posRight[0] = 1; // right is next row
posRight[X] = 0; // right same first column posRight[1] = 0; // right same first column
} }
int ret = FAIL; int ret = FAIL;
@ -1122,7 +1088,7 @@ int Beb_SetDetectorPosition(int pos[]) {
uint32_t value = 0; uint32_t value = 0;
ret = OK; ret = OK;
// x left // x left
int posval = Beb_swap_uint16(posLeft[Y]); int posval = Beb_swap_uint16(posLeft[0]);
value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST); value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST);
value &= UDP_HEADER_ID_MSK; // to keep previous id value value &= UDP_HEADER_ID_MSK; // to keep previous id value
Beb_Write32(csp0base, UDP_HEADER_A_LEFT_OFST, Beb_Write32(csp0base, UDP_HEADER_A_LEFT_OFST,
@ -1134,7 +1100,7 @@ int Beb_SetDetectorPosition(int pos[]) {
ret = FAIL; ret = FAIL;
} }
// x right // x right
posval = Beb_swap_uint16(posRight[Y]); posval = Beb_swap_uint16(posRight[0]);
value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST);
value &= UDP_HEADER_ID_MSK; // to keep previous id value value &= UDP_HEADER_ID_MSK; // to keep previous id value
Beb_Write32(csp0base, UDP_HEADER_A_RIGHT_OFST, Beb_Write32(csp0base, UDP_HEADER_A_RIGHT_OFST,
@ -1147,7 +1113,7 @@ int Beb_SetDetectorPosition(int pos[]) {
} }
// y left (column) // y left (column)
posval = Beb_swap_uint16(posLeft[X]); posval = Beb_swap_uint16(posLeft[1]);
value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST); value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST);
value &= UDP_HEADER_Z_MSK; // to keep previous z value value &= UDP_HEADER_Z_MSK; // to keep previous z value
Beb_Write32(csp0base, UDP_HEADER_B_LEFT_OFST, Beb_Write32(csp0base, UDP_HEADER_B_LEFT_OFST,
@ -1160,7 +1126,7 @@ int Beb_SetDetectorPosition(int pos[]) {
} }
// y right // y right
posval = Beb_swap_uint16(posRight[X]); posval = Beb_swap_uint16(posRight[1]);
value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST); value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST);
value &= UDP_HEADER_Z_MSK; // to keep previous z value value &= UDP_HEADER_Z_MSK; // to keep previous z value
Beb_Write32(csp0base, UDP_HEADER_B_RIGHT_OFST, Beb_Write32(csp0base, UDP_HEADER_B_RIGHT_OFST,
@ -1176,10 +1142,10 @@ int Beb_SetDetectorPosition(int pos[]) {
Beb_close(fd, csp0base); Beb_close(fd, csp0base);
} }
if (ret == OK) { if (ret == OK) {
LOG(logINFO, ("Position set to (col, row):\n" LOG(logINFO, ("Position set to...\n"
"\tLeft: [%d, %d]\n" "\tLeft: [%d, %d]\n"
"\tRight:[%d, %d]\n", "\tRight:[%d, %d]\n",
posLeft[X], posLeft[Y], posRight[X], posRight[Y])); posLeft[0], posLeft[1], posRight[0], posRight[1]));
} }
return ret; return ret;
@ -1259,20 +1225,20 @@ int Beb_GetNextFrameNumber(uint64_t *retval, int tengigaEnable) {
else { else {
uint64_t left10g = uint64_t left10g =
Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_10G_LEFT_MSB_OFST); Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_1G_LEFT_MSB_OFST);
temp = Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_10G_LEFT_LSB_OFST); temp = Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_1G_LEFT_LSB_OFST);
left10g = ((left10g << 32) | temp) >> 16; left10g = ((left10g << 32) | temp) >> 16;
++left10g; // increment for firmware ++left10g; // increment for firmware
uint64_t right10g = uint64_t right10g =
Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_10G_LEFT_MSB_OFST); Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_1G_LEFT_MSB_OFST);
temp = Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_10G_LEFT_LSB_OFST); temp = Beb_Read32(csp0base, UDP_HEADER_GET_FNUM_1G_LEFT_LSB_OFST);
right10g = ((right10g << 32) | temp) >> 16; right10g = ((right10g << 32) | temp) >> 16;
Beb_close(fd, csp0base); Beb_close(fd, csp0base);
++right10g; // increment for firmware ++right10g; // increment for firmware
if (left10g != right10g) { if (left10g != right10g) {
LOG(logERROR, ("Retrieved inconsistent frame numbers from 10g left " LOG(logERROR, ("Retrieved inconsistent frame numbers from `0g left "
"%llu and right %llu\n", "%llu and right %llu\n",
(long long int)left10g, (long long int)right10g)); (long long int)left10g, (long long int)right10g));
*retval = (left10g > right10g) *retval = (left10g > right10g)

View File

@ -15,7 +15,7 @@ int Beb_SetHeaderData(uint64_t src_mac, uint32_t src_ip, uint16_t src_port,
uint64_t dst_mac, uint32_t dst_ip, uint16_t dst_port); uint64_t dst_mac, uint32_t dst_ip, uint16_t dst_port);
void Beb_AdjustIPChecksum(struct udp_header_type *ip); void Beb_AdjustIPChecksum(struct udp_header_type *ip);
int Beb_GetModuleConfiguration(int *master, int *top, int *normal); void Beb_GetModuleConfiguration(int *master, int *top, int *normal);
int Beb_IsTransmitting(int *retval, int tengiga, int waitForDelay); int Beb_IsTransmitting(int *retval, int tengiga, int waitForDelay);
void Beb_SetTopVariable(int val); void Beb_SetTopVariable(int val);

View File

@ -16,31 +16,91 @@ include_directories(
../../slsSupportLib/include ../../slsSupportLib/include
) )
add_executable(eigerDetectorServer_virtual add_executable(eigerDetectorServerMaster_virtual
${src} ${src}
) )
target_include_directories(eigerDetectorServer_virtual target_include_directories(eigerDetectorServerMaster_virtual
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
) )
target_compile_definitions(eigerDetectorServer_virtual target_compile_definitions(eigerDetectorServerMaster_virtual
PUBLIC EIGERD PCCOMPILE STOP_SERVER PUBLIC EIGERD PCCOMPILE STOP_SERVER
PUBLIC VIRTUAL #VIRTUAL_9M PUBLIC VIRTUAL #VIRTUAL_9M
PUBLIC VIRTUAL_MASTER
) )
target_link_libraries(eigerDetectorServer_virtual target_link_libraries(eigerDetectorServerMaster_virtual
PUBLIC pthread rt slsProjectCSettings PUBLIC pthread rt slsProjectCSettings
) )
set_target_properties(eigerDetectorServer_virtual PROPERTIES set_target_properties(eigerDetectorServerMaster_virtual PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
) )
install(TARGETS eigerDetectorServer_virtual install(TARGETS eigerDetectorServerMaster_virtual
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
) )
add_executable(eigerDetectorServerSlaveTop_virtual
${src}
)
target_include_directories(eigerDetectorServerSlaveTop_virtual
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
)
target_compile_definitions(eigerDetectorServerSlaveTop_virtual
PUBLIC EIGERD PCCOMPILE STOP_SERVER
PUBLIC VIRTUAL #VIRTUAL_9M
PUBLIC VIRTUAL_TOP
)
target_link_libraries(eigerDetectorServerSlaveTop_virtual
PUBLIC pthread rt slsProjectCSettings
)
set_target_properties(eigerDetectorServerSlaveTop_virtual PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
install(TARGETS eigerDetectorServerSlaveTop_virtual
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
add_executable(eigerDetectorServerSlaveBottom_virtual
${src}
)
target_include_directories(eigerDetectorServerSlaveBottom_virtual
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
)
target_compile_definitions(eigerDetectorServerSlaveBottom_virtual
PUBLIC EIGERD PCCOMPILE STOP_SERVER
PUBLIC VIRTUAL #VIRTUAL_9M
)
target_link_libraries(eigerDetectorServerSlaveBottom_virtual
PUBLIC pthread rt slsProjectCSettings
)
set_target_properties(eigerDetectorServerSlaveBottom_virtual PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
install(TARGETS eigerDetectorServerSlaveBottom_virtual
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
configure_file(config_eiger.txt ${CMAKE_BINARY_DIR}/bin/config_eiger.txt COPYONLY) configure_file(config_eiger.txt ${CMAKE_BINARY_DIR}/bin/config_eiger.txt COPYONLY)
configure_file(detid_eiger.txt ${CMAKE_BINARY_DIR}/bin/detid_eiger.txt COPYONLY) configure_file(detid_eiger.txt ${CMAKE_BINARY_DIR}/bin/detid_eiger.txt COPYONLY)

View File

@ -18,7 +18,7 @@
const unsigned int Feb_Control_leftAddress = 0x100; const unsigned int Feb_Control_leftAddress = 0x100;
const unsigned int Feb_Control_rightAddress = 0x200; const unsigned int Feb_Control_rightAddress = 0x200;
int Feb_Control_master = -1; int Feb_Control_master = 0;
int Feb_Control_normal = 0; int Feb_Control_normal = 0;
int Feb_Control_activated = 1; int Feb_Control_activated = 1;
@ -50,16 +50,17 @@ double ratemax = -1;
// setup // setup
void Feb_Control_activate(int activate) { Feb_Control_activated = activate; } void Feb_Control_activate(int activate) { Feb_Control_activated = activate; }
int Feb_Control_FebControl(int normal) { void Feb_Control_FebControl() {
Feb_Control_staticBits = 0; Feb_Control_staticBits = Feb_Control_acquireNReadoutMode =
Feb_Control_acquireNReadoutMode = 0; Feb_Control_triggerMode = Feb_Control_externalEnableMode =
Feb_Control_triggerMode = 0;
Feb_Control_externalEnableMode = 0;
Feb_Control_subFrameMode = 0; Feb_Control_subFrameMode = 0;
Feb_Control_trimbit_size = 263680; Feb_Control_trimbit_size = 263680;
Feb_Control_last_downloaded_trimbits = Feb_Control_last_downloaded_trimbits =
malloc(Feb_Control_trimbit_size * sizeof(int)); malloc(Feb_Control_trimbit_size * sizeof(int));
}
int Feb_Control_Init(int master, int normal) {
Feb_Control_master = master;
Feb_Control_normal = normal; Feb_Control_normal = normal;
Feb_Interface_SetAddress(Feb_Control_rightAddress, Feb_Control_leftAddress); Feb_Interface_SetAddress(Feb_Control_rightAddress, Feb_Control_leftAddress);
if (Feb_Control_activated) { if (Feb_Control_activated) {
@ -930,10 +931,7 @@ unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec) {
int Feb_Control_PrepareForAcquisition() { int Feb_Control_PrepareForAcquisition() {
LOG(logINFOBLUE, ("Preparing for Acquisition\n")); LOG(logINFOBLUE, ("Preparing for Acquisition\n"));
if (!Feb_Control_PrintAcquisitionSetup()) { Feb_Control_PrintAcquisitionSetup();
LOG(logERROR, ("Could not prepare acquisition\n"));
return 0;
}
if (Feb_Control_Reset() == STATUS_ERROR) { if (Feb_Control_Reset() == STATUS_ERROR) {
LOG(logERROR, ("Trouble reseting daq or data stream\n")); LOG(logERROR, ("Trouble reseting daq or data stream\n"));
@ -990,26 +988,20 @@ int Feb_Control_PrepareForAcquisition() {
return 1; return 1;
} }
int Feb_Control_PrintAcquisitionSetup() { void Feb_Control_PrintAcquisitionSetup() {
time_t rawtime; time_t rawtime;
time(&rawtime); time(&rawtime);
struct tm *timeinfo = localtime(&rawtime); struct tm *timeinfo = localtime(&rawtime);
int dr = 0; LOG(logINFO,
if (!Feb_Control_GetDynamicRange(&dr)) { ("Starting an exposure: (%s)"
LOG(logERROR, ("Could not print acquisition set up\n"));
return 0;
}
LOG(logINFO, ("Starting an exposure: (%s)"
"\t Dynamic range nbits: %d\n" "\t Dynamic range nbits: %d\n"
"\t Trigger mode: 0x%x\n" "\t Trigger mode: 0x%x\n"
"\t Number of exposures: %d\n" "\t Number of exposures: %d\n"
"\t Exsposure time (if used): %f seconds.\n" "\t Exsposure time (if used): %f seconds.\n"
"\t Exsposure period (if used): %f seconds.\n\n", "\t Exsposure period (if used): %f seconds.\n\n",
asctime(timeinfo), dr, Feb_Control_triggerMode, asctime(timeinfo), Feb_Control_GetDynamicRange(),
Feb_Control_GetNExposures(), Feb_Control_exposure_time_in_sec, Feb_Control_triggerMode, Feb_Control_GetNExposures(),
Feb_Control_exposure_period_in_sec)); Feb_Control_exposure_time_in_sec, Feb_Control_exposure_period_in_sec));
return 1;
} }
int Feb_Control_StartAcquisition() { int Feb_Control_StartAcquisition() {
@ -1177,106 +1169,49 @@ int Feb_Control_SoftwareTrigger(int block) {
} }
// parameters // parameters
int Feb_Control_SetDynamicRange(int dr) { int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo) {
static unsigned int everything_but_bit_mode = DAQ_STATIC_BIT_PROGRAM | static unsigned int everything_but_bit_mode = DAQ_STATIC_BIT_PROGRAM |
DAQ_STATIC_BIT_CHIP_TEST | DAQ_STATIC_BIT_CHIP_TEST |
DAQ_STATIC_BIT_ROTEST; DAQ_STATIC_BIT_ROTEST;
switch (dr) { if (four_eight_sixteen_or_thirtytwo == 4) {
case 4:
Feb_Control_staticBits = Feb_Control_staticBits =
DAQ_STATIC_BIT_M4 | DAQ_STATIC_BIT_M4 |
(Feb_Control_staticBits & (Feb_Control_staticBits &
everything_but_bit_mode); // leave test bits in currernt state everything_but_bit_mode); // leave test bits in currernt state
Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING;
break; } else if (four_eight_sixteen_or_thirtytwo == 8) {
case 8:
Feb_Control_staticBits = DAQ_STATIC_BIT_M8 | (Feb_Control_staticBits & Feb_Control_staticBits = DAQ_STATIC_BIT_M8 | (Feb_Control_staticBits &
everything_but_bit_mode); everything_but_bit_mode);
Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING;
break; } else if (four_eight_sixteen_or_thirtytwo == 16) {
case 12:
case 16:
Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits & Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits &
everything_but_bit_mode); everything_but_bit_mode);
Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING;
} else if (four_eight_sixteen_or_thirtytwo == 32) {
// disable 16 bit conversion if 12 bit mode (enable if 16 bit)
if (!Feb_Control_Disable16bitConversion(dr == 12))
return 0;
break;
case 32:
Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits & Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits &
everything_but_bit_mode); everything_but_bit_mode);
Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING;
break; } else {
default: LOG(logERROR, ("dynamic range (%d) not valid, not setting bit mode.\n",
LOG(logERROR, four_eight_sixteen_or_thirtytwo));
("dynamic range (%d) not valid, not setting bit mode.\n", dr));
LOG(logINFO, ("Set dynamic range int must equal 4,8 16, or 32.\n")); LOG(logINFO, ("Set dynamic range int must equal 4,8 16, or 32.\n"));
return 0; return 0;
} }
LOG(logINFO, ("Dynamic range set to %d\n", dr)); LOG(logINFO,
("Dynamic range set to %d\n", four_eight_sixteen_or_thirtytwo));
return 1; return 1;
} }
int Feb_Control_GetDynamicRange(int *retval) { unsigned int Feb_Control_GetDynamicRange() {
if (Feb_Control_subFrameMode & DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) { if (Feb_Control_subFrameMode & DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING)
*retval = 32; return 32;
} else if (DAQ_STATIC_BIT_M4 & Feb_Control_staticBits) { else if (DAQ_STATIC_BIT_M4 & Feb_Control_staticBits)
*retval = 4; return 4;
} else if (DAQ_STATIC_BIT_M8 & Feb_Control_staticBits) { else if (DAQ_STATIC_BIT_M8 & Feb_Control_staticBits)
*retval = 8; return 8;
} else {
int disable16 = 0;
if (!Feb_Control_Get16bitConversionDisabled(&disable16)) {
LOG(logERROR, ("Could not get dynamic range (12 or 16 bit)\n"));
return 0;
}
if (disable16) {
*retval = 12;
} else {
*retval = 16;
}
}
return 1; return 16;
}
int Feb_Control_Disable16bitConversion(int disable) {
LOG(logINFO, ("%s 16 bit expansion\n", disable ? "Disabling" : "Enabling"));
unsigned int regval = 0;
if (!Feb_Control_ReadRegister(DAQ_REG_HRDWRE, &regval)) {
LOG(logERROR, ("Could not %s 16 bit expansion (bit mode)\n",
(disable ? "disable" : "enable")));
return 0;
}
if (disable) {
regval |= DAQ_REG_HRDWRE_DSBL_16BIT_MSK;
} else {
regval &= ~DAQ_REG_HRDWRE_DSBL_16BIT_MSK;
}
if (!Feb_Control_WriteRegister(DAQ_REG_HRDWRE, regval)) {
LOG(logERROR, ("Could not %s 16 bit expansion (bit mode)\n",
(disable ? "disable" : "enable")));
return 0;
}
return 1;
}
int Feb_Control_Get16bitConversionDisabled(int *ret) {
unsigned int regval = 0;
if (!Feb_Control_ReadRegister(DAQ_REG_HRDWRE, &regval)) {
LOG(logERROR, ("Could not get 16 bit expansion (bit mode)\n"));
return 0;
}
if (regval & DAQ_REG_HRDWRE_DSBL_16BIT_MSK) {
*ret = 1;
} else {
*ret = 0;
}
return 1;
} }
int Feb_Control_SetReadoutSpeed(unsigned int readout_speed) { int Feb_Control_SetReadoutSpeed(unsigned int readout_speed) {
@ -1555,8 +1490,9 @@ int Feb_Control_SetTop(enum TOPINDEX ind, int left, int right) {
return 1; return 1;
} }
int Feb_Control_SetMaster(enum MASTERINDEX ind) { void Feb_Control_SetMasterVariable(int val) { Feb_Control_master = val; }
int Feb_Control_SetMaster(enum MASTERINDEX ind) {
uint32_t offset = DAQ_REG_HRDWRE; uint32_t offset = DAQ_REG_HRDWRE;
unsigned int addr[2] = {Feb_Control_leftAddress, Feb_Control_rightAddress}; unsigned int addr[2] = {Feb_Control_leftAddress, Feb_Control_rightAddress};
char *master_names[] = {MASTER_NAMES}; char *master_names[] = {MASTER_NAMES};
@ -1593,31 +1529,9 @@ int Feb_Control_SetMaster(enum MASTERINDEX ind) {
LOG(logINFOBLUE, ("%s Master flag to %s Feb\n", LOG(logINFOBLUE, ("%s Master flag to %s Feb\n",
(ind == MASTER_HARDWARE ? "Resetting" : "Overwriting"), (ind == MASTER_HARDWARE ? "Resetting" : "Overwriting"),
master_names[ind])); master_names[ind]));
return 1; return 1;
} }
int Feb_Control_SetMasterEffects(int master, int controlServer) {
int prevMaster = Feb_Control_master;
Feb_Control_master = master;
// change in master for 9m
if (controlServer && prevMaster != Feb_Control_master &&
!Feb_Control_normal) {
if (prevMaster) {
Feb_Control_CloseSerialCommunication();
}
if (Feb_Control_master) {
if (!Feb_Control_OpenSerialCommunication()) {
LOG(logERROR, ("Could not intitalize feb control serial "
"communication\n"));
return FAIL;
}
}
}
return OK;
}
int Feb_Control_SetQuad(int val) { int Feb_Control_SetQuad(int val) {
LOG(logINFO, ("Setting Quad to %d in Feb\n", val)); LOG(logINFO, ("Setting Quad to %d in Feb\n", val));
Feb_Control_quadMode = val; Feb_Control_quadMode = val;
@ -1640,10 +1554,7 @@ int Feb_Control_SetChipSignalsToTrimQuad(int enable) {
regval &= ~(DAQ_REG_HRDWRE_PROGRAM_MSK | DAQ_REG_HRDWRE_M8_MSK); regval &= ~(DAQ_REG_HRDWRE_PROGRAM_MSK | DAQ_REG_HRDWRE_M8_MSK);
} }
if (!Feb_Control_WriteRegister(DAQ_REG_HRDWRE, regval)) { return Feb_Control_WriteRegister(DAQ_REG_HRDWRE, regval);
LOG(logERROR, ("Could not set chip signals to trim quad\n"));
return 0;
}
} }
return 1; return 1;
} }
@ -1693,7 +1604,7 @@ int Feb_Control_WriteRegister(uint32_t offset, uint32_t data) {
for (int iloop = 0; iloop < 2; ++iloop) { for (int iloop = 0; iloop < 2; ++iloop) {
if (run[iloop]) { if (run[iloop]) {
LOG(logDEBUG1, LOG(logINFO,
("Writing 0x%x to %s 0x%x\n", data, side[iloop], actualOffset)); ("Writing 0x%x to %s 0x%x\n", data, side[iloop], actualOffset));
if (!Feb_Interface_WriteRegister(addr[iloop], actualOffset, data, 0, if (!Feb_Interface_WriteRegister(addr[iloop], actualOffset, data, 0,
0)) { 0)) {
@ -1701,18 +1612,6 @@ int Feb_Control_WriteRegister(uint32_t offset, uint32_t data) {
side[iloop], actualOffset)); side[iloop], actualOffset));
return 0; return 0;
} }
uint32_t regVal = 0;
if (!Feb_Interface_ReadRegister(addr[iloop], actualOffset,
&regVal)) {
LOG(logERROR, ("Could not read %s register\n", addr[iloop]));
return 0;
}
if (regVal != data) {
LOG(logERROR,
("Could not write %s register. Write 0x%x, read 0x%x\n",
addr[iloop], data, regVal));
return 0;
}
} }
} }
@ -1749,8 +1648,8 @@ int Feb_Control_ReadRegister(uint32_t offset, uint32_t *retval) {
side[iloop], actualOffset)); side[iloop], actualOffset));
return 0; return 0;
} }
LOG(logDEBUG1, ("Read 0x%x from %s 0x%x\n", value[iloop], LOG(logINFO, ("Read 0x%x from %s 0x%x\n", value[iloop], side[iloop],
side[iloop], actualOffset)); actualOffset));
*retval = value[iloop]; *retval = value[iloop];
// if not the other (left, not right OR right, not left), return the // if not the other (left, not right OR right, not left), return the
// value // value
@ -1925,11 +1824,7 @@ int64_t Feb_Control_Get_RateTable_Period_in_nsec() {
int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec) { int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec) {
// period = exptime if 16bit, period = subexptime if 32 bit // period = exptime if 16bit, period = subexptime if 32 bit
int dr = 0; int dr = Feb_Control_GetDynamicRange();
if (!Feb_Control_GetDynamicRange(&dr)) {
LOG(logERROR, ("Could not set rate correction tau\n"));
return 0;
}
double period_in_sec = double period_in_sec =
(double)(Feb_Control_GetSubFrameExposureTime()) / (double)1e9; (double)(Feb_Control_GetSubFrameExposureTime()) / (double)1e9;
if (dr == 16) if (dr == 16)

View File

@ -7,7 +7,8 @@
// setup // setup
void Feb_Control_activate(int activate); void Feb_Control_activate(int activate);
int Feb_Control_FebControl(int normal); void Feb_Control_FebControl();
int Feb_Control_Init(int master, int normal);
int Feb_Control_OpenSerialCommunication(); int Feb_Control_OpenSerialCommunication();
void Feb_Control_CloseSerialCommunication(); void Feb_Control_CloseSerialCommunication();
int Feb_Control_CheckSetup(); int Feb_Control_CheckSetup();
@ -54,7 +55,7 @@ int Feb_Control_ResetChipPartially();
int Feb_Control_SendBitModeToBebServer(); int Feb_Control_SendBitModeToBebServer();
unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec); unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec);
int Feb_Control_PrepareForAcquisition(); int Feb_Control_PrepareForAcquisition();
int Feb_Control_PrintAcquisitionSetup(); void Feb_Control_PrintAcquisitionSetup();
int Feb_Control_StartAcquisition(); int Feb_Control_StartAcquisition();
int Feb_Control_StopAcquisition(); int Feb_Control_StopAcquisition();
int Feb_Control_IsReadyForTrigger(int *readyForTrigger); int Feb_Control_IsReadyForTrigger(int *readyForTrigger);
@ -62,10 +63,8 @@ int Feb_Control_SendSoftwareTrigger();
int Feb_Control_SoftwareTrigger(int block); int Feb_Control_SoftwareTrigger(int block);
// parameters // parameters
int Feb_Control_SetDynamicRange(int dr); int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo);
int Feb_Control_GetDynamicRange(int *retval); unsigned int Feb_Control_GetDynamicRange();
int Feb_Control_Disable16bitConversion(int disable);
int Feb_Control_Get16bitConversionDisabled();
int Feb_Control_SetReadoutSpeed(unsigned int readout_speed); int Feb_Control_SetReadoutSpeed(unsigned int readout_speed);
int Feb_Control_SetReadoutMode(unsigned int readout_mode); int Feb_Control_SetReadoutMode(unsigned int readout_mode);
int Feb_Control_SetTriggerMode(unsigned int trigger_mode); int Feb_Control_SetTriggerMode(unsigned int trigger_mode);
@ -87,8 +86,8 @@ int Feb_Control_Get_Counter_Bit();
int Feb_Control_SetInterruptSubframe(int val); int Feb_Control_SetInterruptSubframe(int val);
int Feb_Control_GetInterruptSubframe(); int Feb_Control_GetInterruptSubframe();
int Feb_Control_SetTop(enum TOPINDEX ind, int left, int right); int Feb_Control_SetTop(enum TOPINDEX ind, int left, int right);
void Feb_Control_SetMasterVariable(int val);
int Feb_Control_SetMaster(enum MASTERINDEX ind); int Feb_Control_SetMaster(enum MASTERINDEX ind);
int Feb_Control_SetMasterEffects(int master, int controlServer);
int Feb_Control_SetQuad(int val); int Feb_Control_SetQuad(int val);
int Feb_Control_SetChipSignalsToTrimQuad(int enable); int Feb_Control_SetChipSignalsToTrimQuad(int enable);
int Feb_Control_SetReadNRows(int value); int Feb_Control_SetReadNRows(int value);

View File

@ -29,8 +29,6 @@
#define DAQ_REG_HRDWRE_OW_MASTER_MSK (0x00000001 << DAQ_REG_HRDWRE_OW_MASTER_OFST) #define DAQ_REG_HRDWRE_OW_MASTER_MSK (0x00000001 << DAQ_REG_HRDWRE_OW_MASTER_OFST)
#define DAQ_REG_HRDWRE_MASTER_OFST (4) #define DAQ_REG_HRDWRE_MASTER_OFST (4)
#define DAQ_REG_HRDWRE_MASTER_MSK (0x00000001 << DAQ_REG_HRDWRE_MASTER_OFST) #define DAQ_REG_HRDWRE_MASTER_MSK (0x00000001 << DAQ_REG_HRDWRE_MASTER_OFST)
#define DAQ_REG_HRDWRE_DSBL_16BIT_OFST (5)
#define DAQ_REG_HRDWRE_DSBL_16BIT_MSK (0x00000001 << DAQ_REG_HRDWRE_DSBL_16BIT_OFST)
#define DAQ_REG_HRDWRE_PROGRAM_OFST (30) #define DAQ_REG_HRDWRE_PROGRAM_OFST (30)
#define DAQ_REG_HRDWRE_PROGRAM_MSK (0x00000001 << DAQ_REG_HRDWRE_PROGRAM_OFST) #define DAQ_REG_HRDWRE_PROGRAM_MSK (0x00000001 << DAQ_REG_HRDWRE_PROGRAM_OFST)
#define DAQ_REG_HRDWRE_M8_OFST (31) #define DAQ_REG_HRDWRE_M8_OFST (31)

View File

@ -19,24 +19,19 @@
#include <pthread.h> #include <pthread.h>
#include <time.h> #include <time.h>
#endif #endif
extern int portno;
// Global variable from slsDetectorServer_funcs // Global variable from slsDetectorServer_funcs
extern int debugflag; extern int debugflag;
extern int updateFlag; extern int updateFlag;
extern udpStruct udpDetails[MAX_UDP_DESTINATION]; extern udpStruct udpDetails[MAX_UDP_DESTINATION];
extern int numUdpDestinations; extern int numUdpDestinations;
extern const enum detectorType myDetectorType; extern const enum detectorType myDetectorType;
extern int ignoreConfigFileFlag;
// Global variable from communication_funcs.c // Global variable from communication_funcs.c
extern int isControlServer; extern int isControlServer;
extern void getMacAddressinString(char *cmac, int size, uint64_t mac); extern void getMacAddressinString(char *cmac, int size, uint64_t mac);
extern void getIpAddressinString(char *cip, uint32_t ip); extern void getIpAddressinString(char *cip, uint32_t ip);
// Variables that will be exported
int masterCommandLine = -1;
int topCommandLine = -1;
int initError = OK; int initError = OK;
int initCheckDone = 0; int initCheckDone = 0;
char initErrorMessage[MAX_STR_LENGTH]; char initErrorMessage[MAX_STR_LENGTH];
@ -93,7 +88,6 @@ int eiger_virtual_read_n_rows = 256;
int eiger_virtual_interrupt_subframe = 0; int eiger_virtual_interrupt_subframe = 0;
int eiger_virtual_left_datastream = 1; int eiger_virtual_left_datastream = 1;
int eiger_virtual_right_datastream = 1; int eiger_virtual_right_datastream = 1;
int eiger_virtual_module_id = 0;
#endif #endif
int defaultDacValues[NDAC] = DEFAULT_DAC_VALS; int defaultDacValues[NDAC] = DEFAULT_DAC_VALS;
@ -231,23 +225,6 @@ int getModuleId(int *ret, char *mess) {
return getModuleIdInFile(ret, mess, ID_FILE); return getModuleIdInFile(ret, mess, ID_FILE);
} }
int updateModuleId() {
int modid = getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
if (initError == FAIL) {
return FAIL;
}
#ifdef VIRTUAL
eiger_virtual_module_id = modid;
#else
if (Beb_SetModuleId(modid) == FAIL) {
initError = FAIL;
strcpy(initErrorMessage, ("Could not get module id from the file"));
return FAIL;
}
#endif
return OK;
}
u_int64_t getDetectorMAC() { u_int64_t getDetectorMAC() {
char mac[255] = ""; char mac[255] = "";
u_int64_t res = 0; u_int64_t res = 0;
@ -327,36 +304,47 @@ u_int32_t getDetectorIP() {
void initControlServer() { void initControlServer() {
LOG(logINFOBLUE, ("Configuring Control server\n")); LOG(logINFOBLUE, ("Configuring Control server\n"));
if (!updateFlag && initError == OK) { if (!updateFlag && initError == OK) {
if (updateModuleConfiguration() == FAIL) { #ifndef VIRTUAL
initCheckDone = 1; int modid = getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
#else
getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
#endif
if (initError == FAIL) {
return; return;
} }
getModuleConfiguration();
#ifndef VIRTUAL #ifndef VIRTUAL
sharedMemory_lockLocalLink(); sharedMemory_lockLocalLink();
Feb_Control_SetMasterVariable(master);
Feb_Interface_FebInterface(); Feb_Interface_FebInterface();
if (!Feb_Control_FebControl(normal)) { Feb_Control_FebControl();
// same addresses for top and bottom
if (!Feb_Control_Init(master, normal)) {
initError = FAIL; initError = FAIL;
sprintf(initErrorMessage, sprintf(initErrorMessage, "Could not intitalize feb control\n");
"Could not intitalize eiger detector sever: feb control\n");
LOG(logERROR, (initErrorMessage)); LOG(logERROR, (initErrorMessage));
initCheckDone = 1; initCheckDone = 1;
sharedMemory_unlockLocalLink(); sharedMemory_unlockLocalLink();
return; return;
} }
if (Feb_Control_SetMasterEffects(master, isControlServer) == FAIL) { // master of 9M, check high voltage serial communication to blackfin
if (master && !normal) {
if (!Feb_Control_OpenSerialCommunication()) {
initError = FAIL; initError = FAIL;
sprintf(initErrorMessage, "Could not intitalize HV for eiger " sprintf(
"detector server: feb control serial " initErrorMessage,
"communication\n"); "Could not intitalize feb control serial communication\n");
LOG(logERROR, (initErrorMessage)); LOG(logERROR, (initErrorMessage));
initCheckDone = 1; initCheckDone = 1;
sharedMemory_unlockLocalLink(); sharedMemory_unlockLocalLink();
return; return;
} }
}
sharedMemory_unlockLocalLink(); sharedMemory_unlockLocalLink();
LOG(logDEBUG1, ("Control server: FEB Initialization done\n")); LOG(logDEBUG1, ("Control server: FEB Initialization done\n"));
Beb_SetTopVariable(top); Beb_SetTopVariable(top);
Beb_Beb(); Beb_Beb();
Beb_SetModuleId(modid);
LOG(logDEBUG1, ("Control server: BEB Initialization done\n")); LOG(logDEBUG1, ("Control server: BEB Initialization done\n"));
#endif #endif
// also reads config file and deactivates // also reads config file and deactivates
@ -366,126 +354,73 @@ void initControlServer() {
} }
void initStopServer() { void initStopServer() {
if (!updateFlag && initError == OK) { #ifdef VIRTUAL
// wait a few s (control server is setting top/master from config file/ LOG(logINFOBLUE, ("Configuring Stop server\n"));
// command line) getModuleConfiguration();
sharedMemory_setStop(0);
// get top/master in virtual
readConfigFile();
#else
// wait a few s (control server is setting top/master from config file)
usleep(WAIT_STOP_SERVER_START); usleep(WAIT_STOP_SERVER_START);
LOG(logINFOBLUE, ("Configuring Stop server\n")); LOG(logINFOBLUE, ("Configuring Stop server\n"));
if (updateModuleConfiguration() == FAIL) { // exit(-1);
initCheckDone = 1; getModuleConfiguration();
return;
}
#ifdef VIRTUAL
sharedMemory_setStop(0);
// force top or master if in config file
if (readConfigFile() == FAIL) {
initCheckDone = 1;
return;
}
// force top or master if in command line
if (checkCommandLineConfiguration() == FAIL) {
initCheckDone = 1;
return;
}
#else
// control server read config file and already set up master/top
sharedMemory_lockLocalLink(); sharedMemory_lockLocalLink();
Feb_Control_SetMasterVariable(master);
Feb_Interface_FebInterface(); Feb_Interface_FebInterface();
if (!Feb_Control_FebControl(normal)) { Feb_Control_FebControl();
initError = FAIL; // same addresses for top and bottom
sprintf(initErrorMessage, "Could not intitalize feb control\n"); Feb_Control_Init(master, normal);
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
sharedMemory_unlockLocalLink();
return;
}
if (Feb_Control_SetMasterEffects(master, isControlServer) == FAIL) {
initError = FAIL;
sprintf(initErrorMessage, "Could not intitalize HV for eiger "
"detector server: feb control serial "
"communication\n");
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
sharedMemory_unlockLocalLink();
return;
}
sharedMemory_unlockLocalLink(); sharedMemory_unlockLocalLink();
LOG(logDEBUG1, ("Stop server: FEB Initialization done\n")); LOG(logDEBUG1, ("Stop server: FEB Initialization done\n"));
Beb_SetTopVariable(top);
Beb_Beb();
LOG(logDEBUG1, ("Control server: BEB Initialization done\n"));
#endif #endif
// client first connect (from shm) will activate // client first connect (from shm) will activate
if (setActivate(0) == FAIL) { if (setActivate(0) == FAIL) {
initError = FAIL; LOG(logERROR, ("Could not deactivate in stop server\n"));
strcpy(initErrorMessage, "Could not deactivate\n");
LOG(logERROR, (initErrorMessage));
} }
} }
initCheckDone = 1;
}
void checkVirtual9MFlag() { void getModuleConfiguration() {
if (initError == FAIL) {
return;
}
#ifdef VIRTUAL #ifdef VIRTUAL
#ifdef VIRTUAL_MASTER
master = 1;
top = 1;
#else
master = 0;
#ifdef VIRTUAL_TOP
top = 1;
#else
top = 0;
#endif
#endif
#ifdef VIRTUAL_9M #ifdef VIRTUAL_9M
normal = 0; normal = 0;
#else #else
normal = 1; normal = 1;
#endif #endif
#endif
}
int updateModuleConfiguration() { #else
if (getModuleConfiguration(&master, &top, &normal) == FAIL) { Beb_GetModuleConfiguration(&master, &top, &normal);
return FAIL;
}
#ifdef VIRTUAL
checkVirtual9MFlag();
#endif #endif
if (isControlServer) { if (isControlServer) {
LOG(logINFOBLUE, LOG(logINFOBLUE,
("Module: %s %s %s\n", (top ? "TOP" : "BOTTOM"), ("Module: %s %s %s\n", (top ? "TOP" : "BOTTOM"),
(master ? "MASTER" : "SLAVE"), (normal ? "NORMAL" : "SPECIAL"))); (master ? "MASTER" : "SLAVE"), (normal ? "NORMAL" : "SPECIAL")));
} }
return OK;
}
int getModuleConfiguration(int *m, int *t, int *n) {
if (initError == FAIL) {
return FAIL;
}
#ifdef VIRTUAL
*m = master;
*t = top;
*n = normal;
#else
if (Beb_GetModuleConfiguration(m, t, n) == FAIL) {
initError = FAIL;
strcpy(initErrorMessage, ("Could not get module configuration\n"));
LOG(logERROR, (initErrorMessage));
return FAIL;
}
#endif
LOG(logDEBUG,
("module config read: master:%d top:%d normal:%d\n", *m, *t, *n));
return OK;
} }
int readConfigFile() { int readConfigFile() {
if (initError == FAIL) { if (initError == FAIL) {
return initError; return initError;
} }
if (ignoreConfigFileFlag) {
LOG(logWARNING, ("Ignoring Config file\n"));
return OK;
}
#ifndef VIRTUAL
// if not found in config file, they will be reset to hardware settings
top = -1;
master = -1; master = -1;
#endif top = -1;
const int fileNameSize = 128; const int fileNameSize = 128;
char fname[fileNameSize]; char fname[fileNameSize];
@ -536,54 +471,91 @@ int readConfigFile() {
// top command // top command
if (!strncmp(line, "top", strlen("top"))) { if (!strncmp(line, "top", strlen("top"))) {
int t = -1;
// cannot scan values // cannot scan values
if (sscanf(line, "%s %d", command, &t) != 2) { if (sscanf(line, "%s %d", command, &top) != 2) {
sprintf(initErrorMessage, sprintf(initErrorMessage,
"Could not scan top commands from on-board server " "Could not scan top commands from on-board server "
"config file. Line:[%s].\n", "config file. Line:[%s].\n",
line); line);
break; break;
} }
if (t != 0 && t != 1) { #ifndef VIRTUAL
sprintf(initErrorMessage, enum TOPINDEX ind = (top == 1 ? OW_TOP : OW_BOTTOM);
"Invalid top argument from on-board server " if (!Beb_SetTop(ind)) {
sprintf(
initErrorMessage,
"Could not overwrite top to %d in Beb from on-board server "
"config file. Line:[%s].\n", "config file. Line:[%s].\n",
line); top, line);
break; break;
} }
if (setTop(t == 1 ? OW_TOP : OW_BOTTOM) == FAIL) { sharedMemory_lockLocalLink();
sprintf(initErrorMessage, if (!Feb_Control_SetTop(ind, 1, 1)) {
"Could not set top from config file. Line:[%s].\n", sprintf(
line); initErrorMessage,
"Could not overwrite top to %d in Feb from on-board server "
"config file. Line:[%s].\n",
top, line);
sharedMemory_unlockLocalLink();
break; break;
} }
sharedMemory_unlockLocalLink();
// validate change
int actual_top = -1, temp = -1, temp2 = -1;
Beb_GetModuleConfiguration(&temp, &actual_top, &temp2);
if (actual_top != top) {
sprintf(initErrorMessage, "Could not set top to %d. Read %d\n",
top, actual_top);
break;
}
Beb_SetTopVariable(top);
#endif
} }
// master command // master command
else if (!strncmp(line, "master", strlen("master"))) { else if (!strncmp(line, "master", strlen("master"))) {
int m = -1;
// cannot scan values // cannot scan values
if (sscanf(line, "%s %d", command, &m) != 2) { if (sscanf(line, "%s %d", command, &master) != 2) {
sprintf(initErrorMessage, sprintf(initErrorMessage,
"Could not scan master commands from on-board server " "Could not scan master commands from on-board server "
"config file. Line:[%s].\n", "config file. Line:[%s].\n",
line); line);
break; break;
} }
if (m != 0 && m != 1) { #ifndef VIRTUAL
enum MASTERINDEX ind = (master == 1 ? OW_MASTER : OW_SLAVE);
if (!Beb_SetMaster(ind)) {
sprintf(initErrorMessage, sprintf(initErrorMessage,
"Invalid master argument from on-board server " "Could not overwrite master to %d in Beb from on-board "
"server "
"config file. Line:[%s].\n", "config file. Line:[%s].\n",
line); master, line);
break; break;
} }
if (setMaster(m == 1 ? OW_MASTER : OW_SLAVE) == FAIL) { sharedMemory_lockLocalLink();
if (!Feb_Control_SetMaster(ind)) {
sprintf(initErrorMessage, sprintf(initErrorMessage,
"Could not set master from config file. Line:[%s].\n", "Could not overwrite master to %d in Feb from on-board "
line); "server "
"config file. Line:[%s].\n",
master, line);
sharedMemory_unlockLocalLink();
break; break;
} }
sharedMemory_unlockLocalLink();
// validate change
int actual_master = -1, temp = -1, temp2 = -1;
Beb_GetModuleConfiguration(&actual_master, &temp, &temp2);
if (actual_master != master) {
sprintf(initErrorMessage,
"Could not set master to %d. Read %d\n", master,
actual_master);
break;
}
sharedMemory_lockLocalLink();
Feb_Control_SetMasterVariable(master);
sharedMemory_unlockLocalLink();
#endif
} }
// other commands // other commands
@ -604,10 +576,8 @@ int readConfigFile() {
LOG(logINFO, ("Successfully read config file\n")); LOG(logINFO, ("Successfully read config file\n"));
} }
#ifndef VIRTUAL
// reset to hardware settings if not in config file (if overwritten) // reset to hardware settings if not in config file (if overwritten)
resetToHardwareSettings(); resetToHardwareSettings();
#endif
return initError; return initError;
} }
@ -619,56 +589,55 @@ void resetToHardwareSettings() {
} }
// top not set in config file // top not set in config file
if (top == -1) { if (top == -1) {
LOG(logINFO, ("Resetting Top to hardware settings\n")); if (!Beb_SetTop(TOP_HARDWARE)) {
if (setTop(TOP_HARDWARE) == FAIL) {
initError = FAIL; initError = FAIL;
strcpy(initErrorMessage, strcpy(initErrorMessage,
"Could not reset Top flag to hardware settings.\n"); "Could not reset Top flag to Beb hardware settings.\n");
LOG(logERROR, ("%s\n\n", initErrorMessage)); LOG(logERROR, ("%s\n\n", initErrorMessage));
return; return;
} }
sharedMemory_lockLocalLink();
if (!Feb_Control_SetTop(TOP_HARDWARE, 1, 1)) {
initError = FAIL;
strcpy(initErrorMessage,
"Could not reset Top flag to Feb hardware settings.\n");
LOG(logERROR, ("%s\n\n", initErrorMessage));
sharedMemory_unlockLocalLink();
return;
}
sharedMemory_unlockLocalLink();
int temp = -1, temp2 = -1;
Beb_GetModuleConfiguration(&temp, &top, &temp2);
Beb_SetTopVariable(top);
} }
// master not set in config file // master not set in config file
if (master == -1) { if (master == -1) {
LOG(logINFO, ("Resetting Master to hardware settings\n")); if (!Beb_SetMaster(TOP_HARDWARE)) {
if (setMaster(MASTER_HARDWARE) == FAIL) {
initError = FAIL; initError = FAIL;
strcpy(initErrorMessage, strcpy(initErrorMessage,
"Could not reset Master flag to hardware settings.\n"); "Could not reset Master flag to Beb hardware settings.\n");
LOG(logERROR, ("%s\n\n", initErrorMessage)); LOG(logERROR, ("%s\n\n", initErrorMessage));
return; return;
} }
sharedMemory_lockLocalLink();
if (!Feb_Control_SetMaster(TOP_HARDWARE)) {
initError = FAIL;
strcpy(initErrorMessage,
"Could not reset Master flag to Feb hardware settings.\n");
LOG(logERROR, ("%s\n\n", initErrorMessage));
sharedMemory_unlockLocalLink();
return;
}
sharedMemory_unlockLocalLink();
int temp = -1, temp2 = -1;
Beb_GetModuleConfiguration(&master, &temp, &temp2);
sharedMemory_lockLocalLink();
Feb_Control_SetMasterVariable(master);
sharedMemory_unlockLocalLink();
} }
#endif #endif
} }
int checkCommandLineConfiguration() {
if (masterCommandLine != -1) {
LOG(logINFO, ("Setting %s from Command Line\n",
(masterCommandLine == 1 ? "Master" : "Slave")));
if (setMaster(masterCommandLine == 1 ? OW_MASTER : OW_SLAVE) == FAIL) {
initError = FAIL;
sprintf(initErrorMessage, "Could not set %s from command line.\n",
(masterCommandLine == 1 ? "Master" : "Slave"));
LOG(logERROR, (initErrorMessage));
return FAIL;
}
}
if (topCommandLine != -1) {
LOG(logINFO, ("Setting %s from Command Line\n",
(topCommandLine == 1 ? "Top" : "Bottom")));
if (setTop(topCommandLine == 1 ? OW_TOP : OW_BOTTOM) == FAIL) {
initError = FAIL;
sprintf(initErrorMessage, "Could not set %s from command line.\n",
(topCommandLine == 1 ? "Top" : "Bottom"));
LOG(logERROR, (initErrorMessage));
return FAIL;
}
}
return OK;
}
/* set up detector */ /* set up detector */
void allocateDetectorStructureMemory() { void allocateDetectorStructureMemory() {
@ -702,29 +671,15 @@ void allocateDetectorStructureMemory() {
} }
void setupDetector() { void setupDetector() {
allocateDetectorStructureMemory(); allocateDetectorStructureMemory();
// force top or master if in config file
if (readConfigFile() == FAIL)
return;
// force top or master if in command line
if (checkCommandLineConfiguration() == FAIL)
return;
LOG(logINFOBLUE,
("Module: %s %s %s\n", (top ? "TOP" : "BOTTOM"),
(master ? "MASTER" : "SLAVE"), (normal ? "NORMAL" : "SPECIAL")));
if (updateModuleId() == FAIL)
return;
LOG(logINFOBLUE, ("Setting Default Parameters\n"));
resetToDefaultDacs(0); resetToDefaultDacs(0);
#ifdef VIRTUAL #ifdef VIRTUAL
sharedMemory_setStatus(IDLE); sharedMemory_setStatus(IDLE);
setupUDPCommParameters(); setupUDPCommParameters();
#endif #endif
LOG(logINFOBLUE, ("Setting Default Parameters\n"));
// setting default measurement parameters // setting default measurement parameters
setNumFrames(DEFAULT_NUM_FRAMES); setNumFrames(DEFAULT_NUM_FRAMES);
setExpTime(DEFAULT_EXPTIME); setExpTime(DEFAULT_EXPTIME);
@ -764,6 +719,14 @@ void setupDetector() {
} }
sharedMemory_unlockLocalLink(); sharedMemory_unlockLocalLink();
#endif #endif
// force top or master if in config file
if (readConfigFile() == FAIL) {
return;
}
LOG(logINFOBLUE,
("Module: %s %s %s\n", (top ? "TOP" : "BOTTOM"),
(master ? "MASTER" : "SLAVE"), (normal ? "NORMAL" : "SPECIAL")));
if (setNumberofDestinations(numUdpDestinations) == FAIL) { if (setNumberofDestinations(numUdpDestinations) == FAIL) {
initError = FAIL; initError = FAIL;
strcpy(initErrorMessage, "Could not set number of udp destinations\n"); strcpy(initErrorMessage, "Could not set number of udp destinations\n");
@ -858,12 +821,10 @@ int readRegister(uint32_t offset, uint32_t *retval) {
/* set parameters - dr, roi */ /* set parameters - dr, roi */
int setDynamicRange(int dr) { int setDynamicRange(int dr) {
if (dr <= 0) { // setting dr
return FAIL; if (dr > 0) {
} LOG(logDEBUG1, ("Setting dynamic range: %d\n", dr));
#ifdef VIRTUAL #ifndef VIRTUAL
LOG(logINFO, ("Setting dynamic range: %d\n", dr));
#else
sharedMemory_lockLocalLink(); sharedMemory_lockLocalLink();
if (Feb_Control_SetDynamicRange(dr)) { if (Feb_Control_SetDynamicRange(dr)) {
if (!Beb_SetUpTransferParameters(dr)) { if (!Beb_SetUpTransferParameters(dr)) {
@ -875,21 +836,14 @@ int setDynamicRange(int dr) {
sharedMemory_unlockLocalLink(); sharedMemory_unlockLocalLink();
#endif #endif
eiger_dynamicrange = dr; eiger_dynamicrange = dr;
return OK;
} }
// getting dr
int getDynamicRange(int *retval) { #ifndef VIRTUAL
#ifdef VIRTUAL
*retval = eiger_dynamicrange;
#else
sharedMemory_lockLocalLink(); sharedMemory_lockLocalLink();
if (!Feb_Control_GetDynamicRange(retval)) { eiger_dynamicrange = Feb_Control_GetDynamicRange();
sharedMemory_unlockLocalLink();
return FAIL;
}
sharedMemory_unlockLocalLink(); sharedMemory_unlockLocalLink();
#endif #endif
return OK; return eiger_dynamicrange;
} }
/* parameters - readout */ /* parameters - readout */
@ -1204,7 +1158,6 @@ int setModule(sls_detector_module myMod, char *mess) {
// if quad, set M8 and PROGRAM manually // if quad, set M8 and PROGRAM manually
if (!Feb_Control_SetChipSignalsToTrimQuad(1)) { if (!Feb_Control_SetChipSignalsToTrimQuad(1)) {
sharedMemory_unlockLocalLink();
return FAIL; return FAIL;
} }
@ -1217,7 +1170,6 @@ int setModule(sls_detector_module myMod, char *mess) {
// if quad, reset M8 and PROGRAM manually // if quad, reset M8 and PROGRAM manually
if (!Feb_Control_SetChipSignalsToTrimQuad(0)) { if (!Feb_Control_SetChipSignalsToTrimQuad(0)) {
sharedMemory_unlockLocalLink();
return FAIL; return FAIL;
} }
@ -1227,7 +1179,6 @@ int setModule(sls_detector_module myMod, char *mess) {
// if quad, reset M8 and PROGRAM manually // if quad, reset M8 and PROGRAM manually
if (!Feb_Control_SetChipSignalsToTrimQuad(0)) { if (!Feb_Control_SetChipSignalsToTrimQuad(0)) {
sharedMemory_unlockLocalLink();
return FAIL; return FAIL;
} }
@ -1499,120 +1450,7 @@ int setHighVoltage(int val) {
/* parameters - timing, extsig */ /* parameters - timing, extsig */
int setMaster(enum MASTERINDEX m) { int isMaster() { return master; }
char *master_names[] = {MASTER_NAMES};
LOG(logINFOBLUE, ("Setting up Master flag as %s\n", master_names[m]));
#ifdef VIRTUAL
switch (m) {
case OW_MASTER:
master = 1;
break;
case OW_SLAVE:
master = 0;
break;
default:
// hardware settings (do nothing)
break;
}
#else
// need to set it only once via the control server
if (isControlServer) {
if (!Beb_SetMaster(m)) {
return FAIL;
}
sharedMemory_lockLocalLink();
if (!Feb_Control_SetMaster(m)) {
sharedMemory_unlockLocalLink();
return FAIL;
}
sharedMemory_unlockLocalLink();
}
// get and update master variable (cannot get from m, could be hardware)
if (isMaster(&master) == FAIL) {
return FAIL;
}
// verify for master and slave (not hardware)
if ((m == OW_MASTER && master == 0) || (m == OW_SLAVE && master == 1)) {
LOG(logERROR,
("could not set master/slave. Master value retrieved %d\n",
master));
return FAIL;
}
// feb variable and hv comms (9m)
sharedMemory_lockLocalLink();
if (Feb_Control_SetMasterEffects(master, isControlServer) == FAIL) {
sharedMemory_unlockLocalLink();
return FAIL;
}
sharedMemory_unlockLocalLink();
#endif
return OK;
}
int isMaster(int *retval) {
int m = -1, t = -1, n = -1;
if (getModuleConfiguration(&m, &t, &n) == FAIL) {
return FAIL;
}
*retval = m;
return OK;
}
int setTop(enum TOPINDEX t) {
char *top_names[] = {TOP_NAMES};
LOG(logINFOBLUE, ("Setting up Top flag as %s\n", top_names[t]));
#ifdef VIRTUAL
switch (t) {
case OW_TOP:
top = 1;
break;
case OW_BOTTOM:
top = 0;
break;
default:
// hardware settings (do nothing)
break;
}
#else
if (!Beb_SetTop(t)) {
return FAIL;
}
sharedMemory_lockLocalLink();
if (!Feb_Control_SetTop(t, 1, 1)) {
sharedMemory_unlockLocalLink();
return FAIL;
}
sharedMemory_unlockLocalLink();
// get and update top variable(cannot get from t, could be hardware)
if (isTop(&top) == FAIL) {
return FAIL;
}
// verify for master and slave (not hardware)
if ((t == OW_TOP && top == 0) || (t == OW_BOTTOM && top == 1)) {
LOG(logERROR,
("could not set top/bottom. Top value retrieved %d\n", top));
return FAIL;
}
Beb_SetTopVariable(top);
#endif
return OK;
}
int isTop(int *retval) {
int m = -1, t = -1, n = -1;
if (getModuleConfiguration(&m, &t, &n) == FAIL) {
return FAIL;
}
*retval = t;
return OK;
}
void setTiming(enum timingMode arg) { void setTiming(enum timingMode arg) {
int ret = 0; int ret = 0;
@ -1662,7 +1500,6 @@ enum timingMode getTiming() {
} }
/* configure mac */ /* configure mac */
int getNumberofUDPInterfaces() { return 2; }
int getNumberofDestinations(int *retval) { int getNumberofDestinations(int *retval) {
#ifdef VIRTUAL #ifdef VIRTUAL
@ -2085,8 +1922,7 @@ int setRateCorrection(
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(); custom_tau_in_nsec = Feb_Control_Get_RateTable_Tau_in_nsec();
int dr = eiger_dynamicrange; int dr = Feb_Control_GetDynamicRange();
// get period = subexptime if 32bit , else period = exptime if 16 bit // get period = subexptime if 32bit , else period = exptime if 16 bit
int64_t actual_period = int64_t actual_period =
Feb_Control_GetSubFrameExposureTime(); // already in nsec Feb_Control_GetSubFrameExposureTime(); // already in nsec
@ -2268,9 +2104,6 @@ int setDataStream(enum portPosition port, int enable) {
LOG(logERROR, ("Invalid setDataStream enable argument: %d\n", enable)); LOG(logERROR, ("Invalid setDataStream enable argument: %d\n", enable));
return FAIL; return FAIL;
} }
LOG(logINFO,
("%s 10GbE %s datastream\n", (enable ? "Enabling" : "Disabling"),
(port == LEFT ? "left" : "right")));
#ifdef VIRTUAL #ifdef VIRTUAL
if (port == LEFT) { if (port == LEFT) {
eiger_virtual_left_datastream = enable; eiger_virtual_left_datastream = enable;
@ -2448,17 +2281,15 @@ void *start_timer(void *arg) {
} }
int skipData = 0; int skipData = 0;
int tgEnable = send_to_ten_gig;
if (!eiger_virtual_activate || if (!eiger_virtual_activate ||
(tgEnable && (!eiger_virtual_left_datastream && !eiger_virtual_right_datastream)) {
(!eiger_virtual_left_datastream && !eiger_virtual_right_datastream))) {
skipData = 1; skipData = 1;
LOG(logWARNING, ("Not sending Left and Right datastream\n")); LOG(logWARNING, ("Not sending Left and Right datastream\n"));
} }
if (tgEnable && !eiger_virtual_left_datastream) { if (!eiger_virtual_left_datastream) {
LOG(logWARNING, ("Not sending Left datastream\n")); LOG(logWARNING, ("Not sending Left datastream\n"));
} }
if (tgEnable && !eiger_virtual_right_datastream) { if (!eiger_virtual_right_datastream) {
LOG(logWARNING, ("Not sending Right datastream\n")); LOG(logWARNING, ("Not sending Right datastream\n"));
} }
@ -2468,14 +2299,15 @@ void *start_timer(void *arg) {
int dr = eiger_dynamicrange; int dr = eiger_dynamicrange;
double bytesPerPixel = (double)dr / 8.00; double bytesPerPixel = (double)dr / 8.00;
int tgEnable = send_to_ten_gig;
int datasize = (tgEnable ? 4096 : 1024); int datasize = (tgEnable ? 4096 : 1024);
int packetsize = datasize + sizeof(sls_detector_header); int packetsize = datasize + sizeof(sls_detector_header);
int maxPacketsPerFrame = (tgEnable ? 4 : 16) * dr; int maxPacketsPerFrame = (tgEnable ? 4 : 16) * dr;
int npixelsx = 256 * 2 * bytesPerPixel; int npixelsx = 256 * 2 * bytesPerPixel;
int databytes = 256 * 256 * 2 * bytesPerPixel; int databytes = 256 * 256 * 2 * bytesPerPixel;
int row = eiger_virtual_detPos[Y]; int row = eiger_virtual_detPos[0];
int colLeft = top ? eiger_virtual_detPos[X] : eiger_virtual_detPos[X] + 1; int colLeft = top ? eiger_virtual_detPos[1] : eiger_virtual_detPos[1] + 1;
int colRight = top ? eiger_virtual_detPos[X] + 1 : eiger_virtual_detPos[X]; int colRight = top ? eiger_virtual_detPos[1] + 1 : eiger_virtual_detPos[1];
int readNRows = getReadNRows(); int readNRows = getReadNRows();
if (readNRows == -1) { if (readNRows == -1) {
@ -2485,7 +2317,7 @@ void *start_timer(void *arg) {
const int maxRows = MAX_ROWS_PER_READOUT; const int maxRows = MAX_ROWS_PER_READOUT;
const int packetsPerFrame = (maxPacketsPerFrame * readNRows) / maxRows; const int packetsPerFrame = (maxPacketsPerFrame * readNRows) / maxRows;
LOG(logDEBUG, LOG(logDEBUG1,
(" dr:%d\n bytesperpixel:%f\n tgenable:%d\n datasize:%d\n " (" dr:%d\n bytesperpixel:%f\n tgenable:%d\n datasize:%d\n "
"packetsize:%d\n maxnumpackes:%d\n npixelsx:%d\n databytes:%d\n", "packetsize:%d\n maxnumpackes:%d\n npixelsx:%d\n databytes:%d\n",
dr, bytesPerPixel, tgEnable, datasize, packetsize, maxPacketsPerFrame, dr, bytesPerPixel, tgEnable, datasize, packetsize, maxPacketsPerFrame,
@ -2502,13 +2334,11 @@ void *start_timer(void *arg) {
npixels /= 2; npixels /= 2;
} }
LOG(logDEBUG1, LOG(logDEBUG1,
("npixels:%d pixelsperpacket:%d\n", npixels, pixelsPerPacket)); ("pixels:%d pixelsperpacket:%d\n", npixels, pixelsPerPacket));
uint8_t *src = (uint8_t *)imageData;
for (int i = 0; i < npixels; ++i) { for (int i = 0; i < npixels; ++i) {
if (i > 0 && i % pixelsPerPacket == 0) { if (i > 0 && i % pixelsPerPacket == 0) {
++pixelVal; ++pixelVal;
} }
switch (dr) { switch (dr) {
case 4: case 4:
*((uint8_t *)(imageData + i)) = *((uint8_t *)(imageData + i)) =
@ -2523,45 +2353,9 @@ void *start_timer(void *arg) {
*((uint8_t *)(imageData + i)) = *((uint8_t *)(imageData + i)) =
eiger_virtual_test_mode ? 0xFE : (uint8_t)pixelVal; eiger_virtual_test_mode ? 0xFE : (uint8_t)pixelVal;
break; break;
case 12:
if (eiger_virtual_test_mode) {
// first 12 bit pixel
// first 8 byte
*src++ = 0xFE;
// second 12bit pixel
++i;
// second 8 byte
*src++ = 0xEF;
// third byte
*src++ = 0xFF;
} else {
// first 12 bit pixel
// first 8 byte
*src++ = (uint8_t)(i & 0xFF);
// second 8 byte (first nibble)
*src = (uint8_t)((i++ >> 8u) & 0xF);
// second 12bit pixel
// second 8 byte (second nibble)
*src++ |= ((uint8_t)(i & 0xF) << 4u);
// third byte
*src++ = (uint8_t)((i >> 4u) & 0xFF);
}
break;
case 16: case 16:
// to debug multi module geometry (row, column) in virtual servers (all pixels
// in a module set to particular value)
#ifdef TEST_MOD_GEOMETRY
if ((i % 1024) < 512) {
*((uint16_t *)(imageData + i * sizeof(uint16_t))) =
top ? (portno % 1900) : ((portno % 1900) + 1);
} else {
*((uint16_t *)(imageData + i * sizeof(uint16_t))) =
top ? ((portno % 1900) + 1) : (portno % 1900);
}
#else
*((uint16_t *)(imageData + i * sizeof(uint16_t))) = *((uint16_t *)(imageData + i * sizeof(uint16_t))) =
eiger_virtual_test_mode ? 0xFFE : (uint16_t)pixelVal; eiger_virtual_test_mode ? 0xFFE : (uint16_t)pixelVal;
#endif
break; break;
case 32: case 32:
*((uint32_t *)(imageData + i * sizeof(uint32_t))) = *((uint32_t *)(imageData + i * sizeof(uint32_t))) =
@ -2613,7 +2407,6 @@ void *start_timer(void *arg) {
header->version = SLS_DETECTOR_HEADER_VERSION; header->version = SLS_DETECTOR_HEADER_VERSION;
header->frameNumber = frameNr + iframes; header->frameNumber = frameNr + iframes;
header->packetNumber = i; header->packetNumber = i;
header->modId = eiger_virtual_module_id;
header->row = row; header->row = row;
header->column = colLeft; header->column = colLeft;
@ -2624,7 +2417,6 @@ void *start_timer(void *arg) {
header->version = SLS_DETECTOR_HEADER_VERSION; header->version = SLS_DETECTOR_HEADER_VERSION;
header->frameNumber = frameNr + iframes; header->frameNumber = frameNr + iframes;
header->packetNumber = i; header->packetNumber = i;
header->modId = eiger_virtual_module_id;
header->row = row; header->row = row;
header->column = colRight; header->column = colRight;
if (eiger_virtual_quad_mode) { if (eiger_virtual_quad_mode) {
@ -2635,27 +2427,9 @@ void *start_timer(void *arg) {
// fill data // fill data
int dstOffset = sizeof(sls_detector_header); int dstOffset = sizeof(sls_detector_header);
int dstOffset2 = sizeof(sls_detector_header); int dstOffset2 = sizeof(sls_detector_header);
if (dr == 12) { {
// multiple of 768,1024,4096
int copysize = 256;
for (int psize = 0; psize < datasize; psize += copysize) {
memcpy(packetData + dstOffset, imageData + srcOffset,
copysize);
memcpy(packetData2 + dstOffset2, imageData + srcOffset2,
copysize);
srcOffset += copysize;
srcOffset2 += copysize;
dstOffset += copysize;
dstOffset2 += copysize;
// reached 1 row (quarter module)
if ((srcOffset % npixelsx) == 0) {
srcOffset += npixelsx;
srcOffset2 += npixelsx;
}
}
} else {
for (int psize = 0; psize < datasize; psize += npixelsx) { for (int psize = 0; psize < datasize; psize += npixelsx) {
if (dr == 32 && tgEnable == 0) { if (dr == 32 && tgEnable == 0) {
memcpy(packetData + dstOffset, memcpy(packetData + dstOffset,
imageData + srcOffset, npixelsx / 2); imageData + srcOffset, npixelsx / 2);
@ -2685,16 +2459,14 @@ void *start_timer(void *arg) {
} }
} }
} }
if ((!tgEnable || if (eiger_virtual_left_datastream && i >= startval &&
(tgEnable && eiger_virtual_left_datastream)) && i <= endval) {
i >= startval && i <= endval) {
usleep(eiger_virtual_transmission_delay_left); usleep(eiger_virtual_transmission_delay_left);
sendUDPPacket(iRxEntry, 0, packetData, packetsize); sendUDPPacket(iRxEntry, 0, packetData, packetsize);
LOG(logDEBUG1, ("Sent left packet: %d\n", i)); LOG(logDEBUG1, ("Sent left packet: %d\n", i));
} }
if ((!tgEnable || if (eiger_virtual_right_datastream && i >= startval &&
(tgEnable && eiger_virtual_right_datastream)) && i <= endval) {
i >= startval && i <= endval) {
usleep(eiger_virtual_transmission_delay_right); usleep(eiger_virtual_transmission_delay_right);
sendUDPPacket(iRxEntry, 1, packetData2, packetsize); sendUDPPacket(iRxEntry, 1, packetData2, packetsize);
LOG(logDEBUG1, ("Sent right packet: %d\n", i)); LOG(logDEBUG1, ("Sent right packet: %d\n", i));
@ -2955,9 +2727,9 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) {
int calculateDataBytes() { int calculateDataBytes() {
if (send_to_ten_gig) if (send_to_ten_gig)
return eiger_dynamicrange * ONE_GIGA_CONSTANT * TEN_GIGA_BUFFER_SIZE; return setDynamicRange(-1) * ONE_GIGA_CONSTANT * TEN_GIGA_BUFFER_SIZE;
else else
return eiger_dynamicrange * TEN_GIGA_CONSTANT * ONE_GIGA_BUFFER_SIZE; return setDynamicRange(-1) * TEN_GIGA_CONSTANT * ONE_GIGA_BUFFER_SIZE;
} }
int getTotalNumberOfChannels() { int getTotalNumberOfChannels() {

View File

@ -5,7 +5,7 @@
#define LINKED_SERVER_NAME "eigerDetectorServer" #define LINKED_SERVER_NAME "eigerDetectorServer"
#define REQUIRED_FIRMWARE_VERSION (30) #define REQUIRED_FIRMWARE_VERSION (29)
// virtual ones renamed for consistency // virtual ones renamed for consistency
// real ones keep previous name for compatibility (already in production) // real ones keep previous name for compatibility (already in production)
#ifdef VIRTUAL #ifdef VIRTUAL
@ -43,7 +43,7 @@ enum DACINDEX {
#define DAC_NAMES \ #define DAC_NAMES \
"VSvP", "Vtrim", "Vrpreamp", "Vrshaper", "VSvN", "Vtgstv", "Vcmp_ll", \ "VSvP", "Vtrim", "Vrpreamp", "Vrshaper", "VSvN", "Vtgstv", "Vcmp_ll", \
"Vcmp_lr", "Vcal", "Vcmp_rl", "rxb_rb", "rxb_lb", "Vcmp_rr", "Vcp", \ "Vcmp_lr", "Vcal", "Vcmp_rl", "rxb_rb", "rxb_lb", "Vcmp_rr", "Vcp", \
"Vcn", "Vishaper", "Vthreshold" "Vcn", "Vishaper"
#define DEFAULT_DAC_VALS \ #define DEFAULT_DAC_VALS \
{ \ { \
0, /* VSvP */ \ 0, /* VSvP */ \

View File

@ -28,16 +28,12 @@ extern int updateFlag;
extern int checkModuleFlag; extern int checkModuleFlag;
extern udpStruct udpDetails[MAX_UDP_DESTINATION]; extern udpStruct udpDetails[MAX_UDP_DESTINATION];
extern const enum detectorType myDetectorType; extern const enum detectorType myDetectorType;
extern int ignoreConfigFileFlag;
// Global variable from communication_funcs.c // Global variable from communication_funcs.c
extern int isControlServer; extern int isControlServer;
extern void getMacAddressinString(char *cmac, int size, uint64_t mac); extern void getMacAddressinString(char *cmac, int size, uint64_t mac);
extern void getIpAddressinString(char *cip, uint32_t ip); extern void getIpAddressinString(char *cip, uint32_t ip);
// Variables that will be exported
int masterCommandLine = -1;
int initError = OK; int initError = OK;
int initCheckDone = 0; int initCheckDone = 0;
char initErrorMessage[MAX_STR_LENGTH]; char initErrorMessage[MAX_STR_LENGTH];
@ -45,7 +41,6 @@ char initErrorMessage[MAX_STR_LENGTH];
#ifdef VIRTUAL #ifdef VIRTUAL
pthread_t pthread_virtual_tid; pthread_t pthread_virtual_tid;
int64_t virtual_currentFrameNumber = 2; int64_t virtual_currentFrameNumber = 2;
int virtual_moduleid = 0;
#endif #endif
enum detectorSettings thisSettings = UNINITIALIZED; enum detectorSettings thisSettings = UNINITIALIZED;
@ -73,7 +68,6 @@ int64_t burstPeriodReg = 0;
int filterResistor = 0; int filterResistor = 0;
int cdsGain = 0; int cdsGain = 0;
int detPos[2] = {}; int detPos[2] = {};
int master = 1;
int isInitCheckDone() { return initCheckDone; } int isInitCheckDone() { return initCheckDone; }
@ -107,9 +101,8 @@ void basictests() {
} }
// does check only if flag is 0 (by default), set by command line // does check only if flag is 0 (by default), set by command line
if ((!debugflag) && (!updateFlag) && if ((!debugflag) && (!updateFlag) &&
((validateKernelVersion(KERNEL_DATE_VRSN) == FAIL) || ((validateKernelVersion(KERNEL_DATE_VRSN) == FAIL) || (checkType() == FAIL) ||
(checkType() == FAIL) || (testFpga() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL))) {
(testBus() == FAIL))) {
sprintf(initErrorMessage, sprintf(initErrorMessage,
"Could not pass basic tests of FPGA and bus. Dangerous to " "Could not pass basic tests of FPGA and bus. Dangerous to "
"continue. (Firmware version:0x%llx) \n", "continue. (Firmware version:0x%llx) \n",
@ -300,18 +293,6 @@ void setModuleId(int modid) {
bus_r(MOD_ID_REG) | ((modid << MOD_ID_OFST) & MOD_ID_MSK)); bus_r(MOD_ID_REG) | ((modid << MOD_ID_OFST) & MOD_ID_MSK));
} }
int updateModuleId() {
int modid = getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
if (initError == FAIL) {
return FAIL;
}
#ifdef VIRTUAL
virtual_moduleid = modid;
#endif
setModuleId(modid);
return OK;
}
u_int64_t getDetectorMAC() { u_int64_t getDetectorMAC() {
#ifdef VIRTUAL #ifdef VIRTUAL
return 0; return 0;
@ -375,28 +356,17 @@ void initControlServer() {
} }
void initStopServer() { void initStopServer() {
if (!updateFlag && initError == OK) {
usleep(CTRL_SRVR_INIT_TIME_US); usleep(CTRL_SRVR_INIT_TIME_US);
LOG(logINFOBLUE, ("Configuring Stop server\n"));
if (mapCSP0() == FAIL) { if (mapCSP0() == FAIL) {
initError = FAIL; LOG(logERROR,
strcpy(initErrorMessage, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"));
"Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); exit(EXIT_FAILURE);
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
return;
} }
#ifdef VIRTUAL #ifdef VIRTUAL
sharedMemory_setStop(0); sharedMemory_setStop(0);
// not reading config file (nothing of interest to stop server)
if (checkCommandLineConfiguration() == FAIL) {
initCheckDone = 1;
return;
}
#endif #endif
} }
initCheckDone = 1;
}
/* set up detector */ /* set up detector */
@ -508,13 +478,12 @@ void setupDetector() {
return; return;
} }
// master for virtual // set module id in register
if (checkCommandLineConfiguration() == FAIL) int modid = getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
return; if (initError == FAIL) {
if (updateModuleId() == FAIL) {
return; return;
} }
setModuleId(modid);
setBurstMode(DEFAULT_BURST_MODE); setBurstMode(DEFAULT_BURST_MODE);
setFilterResistor(DEFAULT_FILTER_RESISTOR); setFilterResistor(DEFAULT_FILTER_RESISTOR);
@ -626,11 +595,6 @@ int readConfigFile() {
return initError; return initError;
} }
if (ignoreConfigFileFlag) {
LOG(logWARNING, ("Ignoring Config file\n"));
return OK;
}
// require a sleep before and after the rst dac signal // require a sleep before and after the rst dac signal
usleep(INITIAL_STARTUP_WAIT); usleep(INITIAL_STARTUP_WAIT);
@ -955,21 +919,6 @@ int readConfigFile() {
return initError; return initError;
} }
int checkCommandLineConfiguration() {
if (masterCommandLine != -1) {
#ifdef VIRTUAL
master = masterCommandLine;
#else
initError = FAIL;
strcpy(initErrorMessage,
"Cannot set Master from command line for this detector. "
"Should have been caught before!\n");
return FAIL;
#endif
}
return OK;
}
/* firmware functions (resets) */ /* firmware functions (resets) */
void cleanFifos() { void cleanFifos() {
@ -998,16 +947,7 @@ void resetPeripheral() {
/* set parameters - dr, roi */ /* set parameters - dr, roi */
int setDynamicRange(int dr) { int setDynamicRange(int dr) { return DYNAMIC_RANGE; }
if (dr == 16)
return OK;
return FAIL;
}
int getDynamicRange(int *retval) {
*retval = DYNAMIC_RANGE;
return OK;
}
/* parameters - timer */ /* parameters - timer */
void setNumFrames(int64_t val) { void setNumFrames(int64_t val) {
@ -1497,11 +1437,6 @@ int setHighVoltage(int val) {
/* parameters - timing */ /* parameters - timing */
int isMaster(int *retval) {
*retval = master;
return OK;
}
void updatingRegisters() { void updatingRegisters() {
LOG(logINFO, ("\tUpdating registers\n")); LOG(logINFO, ("\tUpdating registers\n"));
// burst // burst
@ -1917,7 +1852,7 @@ int setDetectorPosition(int pos[]) {
int ret = OK; int ret = OK;
// row // row
value = detPos[Y]; value = detPos[X];
bus_w(addr, (bus_r(addr) & ~COORD_ROW_MSK) | bus_w(addr, (bus_r(addr) & ~COORD_ROW_MSK) |
((value << COORD_ROW_OFST) & COORD_ROW_MSK)); ((value << COORD_ROW_OFST) & COORD_ROW_MSK));
valueRead = ((bus_r(addr) & COORD_ROW_MSK) >> COORD_ROW_OFST); valueRead = ((bus_r(addr) & COORD_ROW_MSK) >> COORD_ROW_OFST);
@ -1928,7 +1863,7 @@ int setDetectorPosition(int pos[]) {
} }
// col // col
value = detPos[X]; value = detPos[Y];
bus_w(addr, (bus_r(addr) & ~COORD_COL_MSK) | bus_w(addr, (bus_r(addr) & ~COORD_COL_MSK) |
((value << COORD_COL_OFST) & COORD_COL_MSK)); ((value << COORD_COL_OFST) & COORD_COL_MSK));
valueRead = ((bus_r(addr) & COORD_COL_MSK) >> COORD_COL_OFST); valueRead = ((bus_r(addr) & COORD_COL_MSK) >> COORD_COL_OFST);
@ -1939,8 +1874,7 @@ int setDetectorPosition(int pos[]) {
} }
if (ret == OK) { if (ret == OK) {
LOG(logINFO, LOG(logINFO, ("\tPosition set to [%d, %d]\n", detPos[X], detPos[Y]));
("\tPosition set to [%d, %d] #(col, row)\n", detPos[X], detPos[Y]));
} }
return ret; return ret;
@ -1982,17 +1916,9 @@ int checkDetectorType() {
return -2; return -2;
} }
if (abs(type - TYPE_GOTTHARD2_25UM_MASTER_MODULE_VAL) <= TYPE_TOLERANCE) { if ((abs(type - TYPE_GOTTHARD2_MODULE_VAL) > TYPE_TOLERANCE) &&
LOG(logINFOBLUE, ("MASTER 25um Module\n")); (abs(type - TYPE_GOTTHARD2_25UM_MASTER_MODULE_VAL) > TYPE_TOLERANCE) &&
master = 1; (abs(type - TYPE_GOTTHARD2_25UM_SLAVE_MODULE_VAL) > TYPE_TOLERANCE)) {
} else if (abs(type - TYPE_GOTTHARD2_25UM_SLAVE_MODULE_VAL) <=
TYPE_TOLERANCE) {
master = 0;
LOG(logINFOBLUE, ("SLAVE 25um Module\n"));
} else if (abs(type - TYPE_GOTTHARD2_MODULE_VAL) <= TYPE_TOLERANCE) {
master = -1;
LOG(logINFOBLUE, ("50um Module\n"));
} else {
LOG(logERROR, LOG(logERROR,
("Wrong Module attached! Expected %d, %d or %d for Gotthard2, got " ("Wrong Module attached! Expected %d, %d or %d for Gotthard2, got "
"%d\n", "%d\n",
@ -2157,56 +2083,40 @@ int setReadoutSpeed(int val) {
case G2_108MHZ: case G2_108MHZ:
LOG(logINFOBLUE, ("Setting readout speed to 108 MHz\n")); LOG(logINFOBLUE, ("Setting readout speed to 108 MHz\n"));
if (setClockDivider(READOUT_C0, SPEED_108_CLKDIV_0) == FAIL) { if (setClockDivider(READOUT_C0, SPEED_108_CLKDIV_0) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set readout clk 0 to %d\n", SPEED_108_CLKDIV_0));
"set readout clk 0 to %d\n",
SPEED_108_CLKDIV_0));
return FAIL; return FAIL;
} }
if (setClockDivider(READOUT_C1, SPEED_108_CLKDIV_1) == FAIL) { if (setClockDivider(READOUT_C1, SPEED_108_CLKDIV_1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set readout clk 1 to %d\n", SPEED_108_CLKDIV_1));
"set readout clk 1 to %d\n",
SPEED_108_CLKDIV_1));
return FAIL; return FAIL;
} }
if (setPhase(READOUT_C1, SPEED_108_CLKPHASE_DEG_1, 1) == FAIL) { if (setPhase(READOUT_C1, SPEED_108_CLKPHASE_DEG_1, 1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set clk phase 1 %d deg\n", SPEED_108_CLKPHASE_DEG_1));
"set clk phase 1 %d deg\n",
SPEED_108_CLKPHASE_DEG_1));
return FAIL; return FAIL;
} }
setDBITPipeline(SPEED_144_DBIT_PIPELINE); setDBITPipeline(SPEED_144_DBIT_PIPELINE);
if (getDBITPipeline() != SPEED_144_DBIT_PIPELINE) { if (getDBITPipeline() != SPEED_144_DBIT_PIPELINE) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set dbitpipeline to %d \n", SPEED_144_DBIT_PIPELINE));
"set dbitpipeline to %d \n",
SPEED_144_DBIT_PIPELINE));
return FAIL; return FAIL;
} }
break; break;
case G2_144MHZ: case G2_144MHZ:
LOG(logINFOBLUE, ("Setting readout speed to 144 MHz\n")); LOG(logINFOBLUE, ("Setting readout speed to 144 MHz\n"));
if (setClockDivider(READOUT_C0, SPEED_144_CLKDIV_0) == FAIL) { if (setClockDivider(READOUT_C0, SPEED_144_CLKDIV_0) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set readout clk 0 to %d\n", SPEED_144_CLKDIV_0));
"set readout clk 0 to %d\n",
SPEED_144_CLKDIV_0));
return FAIL; return FAIL;
} }
if (setClockDivider(READOUT_C1, SPEED_144_CLKDIV_1) == FAIL) { if (setClockDivider(READOUT_C1, SPEED_144_CLKDIV_1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set readout clk 1 to %d\n", SPEED_144_CLKDIV_1));
"set readout clk 1 to %d\n",
SPEED_144_CLKDIV_1));
return FAIL; return FAIL;
} }
if (setPhase(READOUT_C1, SPEED_144_CLKPHASE_DEG_1, 1) == FAIL) { if (setPhase(READOUT_C1, SPEED_144_CLKPHASE_DEG_1, 1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set clk phase 1 %d deg\n", SPEED_144_CLKPHASE_DEG_1));
"set clk phase 1 %d deg\n",
SPEED_144_CLKPHASE_DEG_1));
return FAIL; return FAIL;
} }
setDBITPipeline(SPEED_144_DBIT_PIPELINE); setDBITPipeline(SPEED_144_DBIT_PIPELINE);
if (getDBITPipeline() != SPEED_144_DBIT_PIPELINE) { if (getDBITPipeline() != SPEED_144_DBIT_PIPELINE) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to " LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set dbitpipeline to %d \n", SPEED_144_DBIT_PIPELINE));
"set dbitpipeline to %d \n",
SPEED_144_DBIT_PIPELINE));
return FAIL; return FAIL;
} }
break; break;
@ -3095,9 +3005,9 @@ void *start_timer(void *arg) {
header->version = SLS_DETECTOR_HEADER_VERSION - 1; header->version = SLS_DETECTOR_HEADER_VERSION - 1;
header->frameNumber = virtual_currentFrameNumber; header->frameNumber = virtual_currentFrameNumber;
header->packetNumber = 0; header->packetNumber = 0;
header->modId = virtual_moduleid; header->modId = 0;
header->row = detPos[Y]; header->row = detPos[X];
header->column = detPos[X]; header->column = detPos[Y];
// fill data // fill data
memcpy(packetData + sizeof(sls_detector_header), imageData, memcpy(packetData + sizeof(sls_detector_header), imageData,
datasize); datasize);

View File

@ -25,11 +25,9 @@ extern int debugflag;
extern int updateFlag; extern int updateFlag;
extern udpStruct udpDetails[MAX_UDP_DESTINATION]; extern udpStruct udpDetails[MAX_UDP_DESTINATION];
extern const enum detectorType myDetectorType; extern const enum detectorType myDetectorType;
extern int ignoreConfigFileFlag;
// Variables that will be exported // Variables that will be exported
int phaseShift = DEFAULT_PHASE_SHIFT; int phaseShift = DEFAULT_PHASE_SHIFT;
int masterCommandLine = -1;
// Global variable from communication_funcs.c // Global variable from communication_funcs.c
extern int isControlServer; extern int isControlServer;
@ -361,28 +359,16 @@ void initControlServer() {
} }
void initStopServer() { void initStopServer() {
if (!updateFlag && initError == OK) {
usleep(CTRL_SRVR_INIT_TIME_US);
LOG(logINFOBLUE, ("Configuring Stop server\n"));
if (mapCSP0() == FAIL) { if (mapCSP0() == FAIL) {
initError = FAIL; LOG(logERROR,
strcpy(initErrorMessage, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"));
"Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); exit(EXIT_FAILURE);
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
return;
} }
#ifdef VIRTUAL #ifdef VIRTUAL
sharedMemory_setStop(0); sharedMemory_setStop(0);
#endif #endif
// to get master from file // to get master from file
if (readConfigFile() == FAIL || readConfigFile();
checkCommandLineConfiguration() == FAIL) {
initCheckDone = 1;
return;
}
}
initCheckDone = 1;
} }
/* set up detector */ /* set up detector */
@ -435,13 +421,6 @@ void setupDetector() {
setROI(rois); // set adcsyncreg, daqreg, chipofinterestreg, cleanfifos, setROI(rois); // set adcsyncreg, daqreg, chipofinterestreg, cleanfifos,
setGbitReadout(); setGbitReadout();
// no config file or not first time server
if (readConfigFile() == FAIL)
return;
if (checkCommandLineConfiguration() == FAIL)
return;
// master, slave (25um) // master, slave (25um)
setMasterSlaveConfiguration(); setMasterSlaveConfiguration();
@ -645,16 +624,6 @@ void setGbitReadout() {
} }
int readConfigFile() { int readConfigFile() {
if (initError == FAIL) {
return initError;
}
if (ignoreConfigFileFlag) {
LOG(logWARNING, ("Ignoring Config file\n"));
return OK;
}
const int fileNameSize = 128; const int fileNameSize = 128;
char fname[fileNameSize]; char fname[fileNameSize];
if (getAbsPath(fname, fileNameSize, CONFIG_FILE) == FAIL) { if (getAbsPath(fname, fileNameSize, CONFIG_FILE) == FAIL) {
@ -678,6 +647,7 @@ int readConfigFile() {
memset(key, 0, keySize); memset(key, 0, keySize);
char value[keySize]; char value[keySize];
memset(value, 0, keySize); memset(value, 0, keySize);
int scan = OK;
// keep reading a line // keep reading a line
while (fgets(line, lineSize, fd)) { while (fgets(line, lineSize, fd)) {
@ -697,22 +667,19 @@ int readConfigFile() {
master = 0; master = 0;
LOG(logINFOBLUE, ("\tSlave or No Master\n")); LOG(logINFOBLUE, ("\tSlave or No Master\n"));
} else { } else {
initError = FAIL; LOG(logERROR,
sprintf( ("\tCould not scan masterflags %s value from config file\n",
initErrorMessage, value));
"Could not scan masterflags %s value from config file\n", scan = FAIL;
value); break;
LOG(logERROR, (initErrorMessage))
fclose(fd);
return FAIL;
} }
// not first server since detector power on // not first server since detector power on
if (!detectorFirstServer) { if (!detectorFirstServer) {
LOG(logWARNING, ("\tServer has been started up before. " LOG(logINFOBLUE, ("\tServer has been started up before. "
"Ignoring rest of config file\n")); "Ignoring rest of config file\n"));
fclose(fd); fclose(fd);
return OK; return FAIL;
} }
} }
@ -721,14 +688,11 @@ int readConfigFile() {
// convert value to int // convert value to int
int ival = 0; int ival = 0;
if (sscanf(value, "%d", &ival) <= 0) { if (sscanf(value, "%d", &ival) <= 0) {
initError = FAIL; LOG(logERROR, ("\tCould not scan parameter %s value %s from "
sprintf(initErrorMessage,
"Could not scan parameter %s value %s from "
"config file\n", "config file\n",
key, value); key, value));
LOG(logERROR, (initErrorMessage)) scan = FAIL;
fclose(fd); break;
return FAIL;
} }
// set value // set value
if (!strcasecmp(key, "masterdefaultdelay")) if (!strcasecmp(key, "masterdefaultdelay"))
@ -746,16 +710,16 @@ int readConfigFile() {
else if (!strcasecmp(key, "startacqdelay")) else if (!strcasecmp(key, "startacqdelay"))
startacqdelay = ival; startacqdelay = ival;
else { else {
initError = FAIL; LOG(logERROR,
sprintf(initErrorMessage, ("\tCould not scan parameter %s from config file\n", key));
"Could not scan parameter %s from config file\n", key); scan = FAIL;
LOG(logERROR, (initErrorMessage)) break;
fclose(fd);
return FAIL;
} }
} }
} }
fclose(fd); fclose(fd);
if (scan == FAIL)
exit(EXIT_FAILURE);
LOG(logINFOBLUE, LOG(logINFOBLUE,
("\tmasterdefaultdelay:%d\n" ("\tmasterdefaultdelay:%d\n"
@ -770,28 +734,13 @@ int readConfigFile() {
return OK; return OK;
} }
int checkCommandLineConfiguration() {
if (masterCommandLine != -1) {
#ifdef VIRTUAL
master = masterCommandLine;
#else
initError = FAIL;
strcpy(initErrorMessage,
"Cannot set Master from command line for this detector. "
"Should have been caught before!\n");
return FAIL;
#endif
}
return OK;
}
void setMasterSlaveConfiguration() { void setMasterSlaveConfiguration() {
// not the first time its being read
if (!detectorFirstServer) {
return;
}
LOG(logINFO, ("Reading Master Slave Configuration\n")); LOG(logINFO, ("Reading Master Slave Configuration\n"));
// no config file or not first time server
if (readConfigFile() == FAIL)
return;
// master configuration // master configuration
if (master) { if (master) {
// master default delay set, so reset delay // master default delay set, so reset delay
@ -839,16 +788,7 @@ void setMasterSlaveConfiguration() {
/* set parameters - dr, roi */ /* set parameters - dr, roi */
int setDynamicRange(int dr) { int setDynamicRange(int dr) { return DYNAMIC_RANGE; }
if (dr == 16)
return OK;
return FAIL;
}
int getDynamicRange(int *retval) {
*retval = DYNAMIC_RANGE;
return OK;
}
int setROI(ROI arg) { int setROI(ROI arg) {
@ -1298,10 +1238,7 @@ int setHighVoltage(int val) {
/* parameters - timing, extsig */ /* parameters - timing, extsig */
int isMaster(int *retval) { int isMaster() { return master; }
*retval = master;
return OK;
}
void setTiming(enum timingMode arg) { void setTiming(enum timingMode arg) {
u_int32_t addr = EXT_SIGNAL_REG; u_int32_t addr = EXT_SIGNAL_REG;
@ -1362,8 +1299,6 @@ int getExtSignal(int signalIndex) {
/* configure mac */ /* configure mac */
int getNumberofUDPInterfaces() { return 1; }
void calcChecksum(mac_conf *mac, int sourceip, int destip) { void calcChecksum(mac_conf *mac, int sourceip, int destip) {
mac->ip.ip_ver = 0x4; mac->ip.ip_ver = 0x4;
mac->ip.ip_ihl = 0x5; mac->ip.ip_ihl = 0x5;

View File

@ -21,14 +21,13 @@
#include <pthread.h> #include <pthread.h>
#include <time.h> #include <time.h>
#endif #endif
extern int portno;
// Global variable from slsDetectorServer_funcs // Global variable from slsDetectorServer_funcs
extern int debugflag; extern int debugflag;
extern int updateFlag; extern int updateFlag;
extern udpStruct udpDetails[MAX_UDP_DESTINATION]; extern udpStruct udpDetails[MAX_UDP_DESTINATION];
extern int numUdpDestinations; extern int numUdpDestinations;
extern const enum detectorType myDetectorType; extern const enum detectorType myDetectorType;
extern int ignoreConfigFileFlag;
// Global variable from communication_funcs.c // Global variable from communication_funcs.c
extern int isControlServer; extern int isControlServer;
@ -393,20 +392,12 @@ void initControlServer() {
} }
void initStopServer() { void initStopServer() {
if (!updateFlag && initError == OK) {
usleep(CTRL_SRVR_INIT_TIME_US); usleep(CTRL_SRVR_INIT_TIME_US);
LOG(logINFOBLUE, ("Configuring Stop server\n"));
if (mapCSP0() == FAIL) { if (mapCSP0() == FAIL) {
initError = FAIL; LOG(logERROR,
strcpy(initErrorMessage, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"));
"Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); exit(EXIT_FAILURE);
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
return;
}
if (readConfigFile() == FAIL) {
initCheckDone = 1;
return;
} }
#ifdef VIRTUAL #ifdef VIRTUAL
sharedMemory_setStop(0); sharedMemory_setStop(0);
@ -415,8 +406,6 @@ void initStopServer() {
setTemperatureEvent(0); setTemperatureEvent(0);
#endif #endif
} }
initCheckDone = 1;
}
/* set up detector */ /* set up detector */
@ -654,11 +643,6 @@ int readConfigFile() {
return initError; return initError;
} }
if (ignoreConfigFileFlag) {
LOG(logWARNING, ("Ignoring Config file\n"));
return OK;
}
const int fileNameSize = 128; const int fileNameSize = 128;
char fname[fileNameSize]; char fname[fileNameSize];
if (getAbsPath(fname, fileNameSize, CONFIG_FILE) == FAIL) { if (getAbsPath(fname, fileNameSize, CONFIG_FILE) == FAIL) {
@ -812,16 +796,7 @@ void resetPeripheral() {
/* set parameters - dr, roi */ /* set parameters - dr, roi */
int setDynamicRange(int dr) { int setDynamicRange(int dr) { return DYNAMIC_RANGE; }
if (dr == 16)
return OK;
return FAIL;
}
int getDynamicRange(int *retval) {
*retval = DYNAMIC_RANGE;
return OK;
}
void setADCInvertRegister(uint32_t val) { void setADCInvertRegister(uint32_t val) {
LOG(logINFO, ("Setting ADC Port Invert Reg to 0x%x\n", val)); LOG(logINFO, ("Setting ADC Port Invert Reg to 0x%x\n", val));
@ -1621,7 +1596,6 @@ int configureMAC() {
int setDetectorPosition(int pos[]) { int setDetectorPosition(int pos[]) {
int ret = OK; int ret = OK;
// row, col
uint32_t innerPos[2] = {pos[X], pos[Y]}; uint32_t innerPos[2] = {pos[X], pos[Y]};
uint32_t outerPos[2] = {pos[X], pos[Y]}; uint32_t outerPos[2] = {pos[X], pos[Y]};
int selInterface = getPrimaryInterface(); int selInterface = getPrimaryInterface();
@ -1631,16 +1605,15 @@ int setDetectorPosition(int pos[]) {
("Setting detector position: 1 Interface %s \n(%d, %d)\n", ("Setting detector position: 1 Interface %s \n(%d, %d)\n",
(selInterface ? "Inner" : "Outer"), innerPos[X], innerPos[Y])); (selInterface ? "Inner" : "Outer"), innerPos[X], innerPos[Y]));
} else { } else {
// top has row incremented by 1 ++outerPos[X];
++innerPos[Y];
LOG(logDEBUG, ("Setting detector position: 2 Interfaces \n" LOG(logDEBUG, ("Setting detector position: 2 Interfaces \n"
" inner top(%d, %d), outer bottom(%d, %d)\n", " inner top(%d, %d), outer bottom(%d, %d)\n",
innerPos[X], innerPos[Y], outerPos[X], outerPos[Y])); innerPos[X], innerPos[Y], outerPos[X], outerPos[Y]));
} }
detPos[0] = innerPos[X]; detPos[0] = innerPos[0];
detPos[1] = innerPos[Y]; detPos[1] = innerPos[1];
detPos[2] = outerPos[X]; detPos[2] = outerPos[0];
detPos[3] = outerPos[Y]; detPos[3] = outerPos[1];
// row // row
// outer // outer
@ -1678,8 +1651,8 @@ int setDetectorPosition(int pos[]) {
if (ret == OK) { if (ret == OK) {
if (getNumberofUDPInterfaces() == 1) { if (getNumberofUDPInterfaces() == 1) {
LOG(logINFOBLUE, ("Position set to [%d, %d] #(col, row)\n", LOG(logINFOBLUE,
innerPos[X], innerPos[Y])); ("Position set to [%d, %d]\n", innerPos[X], innerPos[Y]));
} else { } else {
LOG(logINFOBLUE, (" Inner (top) position set to [%d, %d]\n", LOG(logINFOBLUE, (" Inner (top) position set to [%d, %d]\n",
innerPos[X], innerPos[Y])); innerPos[X], innerPos[Y]));
@ -2533,16 +2506,8 @@ void *start_timer(void *arg) {
if (i > 0 && i % pixelsPerPacket == 0) { if (i > 0 && i % pixelsPerPacket == 0) {
++pixelVal; ++pixelVal;
} }
// to debug multi module geometry (row, column) in virtual servers (all pixels
// in a module set to particular value)
#ifdef TEST_MOD_GEOMETRY
*((uint16_t *)(imageData + i * sizeof(uint16_t))) =
portno % 1900 + (i >= npixels / 2 ? 1 : 0);
#else
*((uint16_t *)(imageData + i * sizeof(uint16_t))) = *((uint16_t *)(imageData + i * sizeof(uint16_t))) =
virtual_image_test_mode ? 0x0FFE : (uint16_t)pixelVal; virtual_image_test_mode ? 0x0FFE : (uint16_t)pixelVal;
#endif
} }
} }
@ -2567,10 +2532,6 @@ void *start_timer(void *arg) {
int srcOffset = 0; int srcOffset = 0;
int srcOffset2 = DATA_BYTES / 2; int srcOffset2 = DATA_BYTES / 2;
int row0 = (numInterfaces == 1 ? detPos[1] : detPos[3]);
int col0 = (numInterfaces == 1 ? detPos[0] : detPos[2]);
int row1 = detPos[1];
int col1 = detPos[0];
// loop packet (128 packets) // loop packet (128 packets)
for (int i = 0; i != maxPacketsPerFrame; ++i) { for (int i = 0; i != maxPacketsPerFrame; ++i) {
@ -2590,8 +2551,8 @@ void *start_timer(void *arg) {
header->frameNumber = frameNr + iframes; header->frameNumber = frameNr + iframes;
header->packetNumber = pnum; header->packetNumber = pnum;
header->modId = 0; header->modId = 0;
header->row = row0; header->row = detPos[0];
header->column = col0; header->column = detPos[1];
// fill data // fill data
memcpy(packetData + sizeof(sls_detector_header), memcpy(packetData + sizeof(sls_detector_header),
@ -2617,8 +2578,8 @@ void *start_timer(void *arg) {
header->frameNumber = frameNr + iframes; header->frameNumber = frameNr + iframes;
header->packetNumber = pnum; header->packetNumber = pnum;
header->modId = 0; header->modId = 0;
header->row = row1; header->row = detPos[2];
header->column = col1; header->column = detPos[3];
// fill data // fill data
memcpy(packetData2 + sizeof(sls_detector_header), memcpy(packetData2 + sizeof(sls_detector_header),

View File

@ -165,9 +165,11 @@
#define PATTERN_OUT_LSB_REG (0x20 << MEM_MAP_SHIFT) #define PATTERN_OUT_LSB_REG (0x20 << MEM_MAP_SHIFT)
#define PATTERN_OUT_MSB_REG (0x21 << MEM_MAP_SHIFT) #define PATTERN_OUT_MSB_REG (0x21 << MEM_MAP_SHIFT)
/* Frame number of next acquisition register (64 bit register) */ /* Frames From Start 64 bit RO register TODO */
#define NEXT_FRAME_NUMB_LOCAL_LSB_REG (0x22 << MEM_MAP_SHIFT) //#define FRAMES_FROM_START_LSB_REG (0x22 << MEM_MAP_SHIFT) // Not
#define NEXT_FRAME_NUMB_LOCAL_MSB_REG (0x23 << MEM_MAP_SHIFT) // 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 */ /* 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_LSB_REG (0x24 << MEM_MAP_SHIFT)

View File

@ -43,6 +43,7 @@ char initErrorMessage[MAX_STR_LENGTH];
#ifdef VIRTUAL #ifdef VIRTUAL
pthread_t pthread_virtual_tid; pthread_t pthread_virtual_tid;
int64_t virtual_currentFrameNumber = 2;
#endif #endif
// 1g readout // 1g readout
@ -67,13 +68,7 @@ int defaultDacValues[NDAC] = DEFAULT_DAC_VALS;
int vLimit = 0; int vLimit = 0;
enum detectorSettings thisSettings = UNINITIALIZED; enum detectorSettings thisSettings = UNINITIALIZED;
int highvoltage = 0; int highvoltage = 0;
// getNumberofchannels return 0 for y in --update mode (virtual servers)
#ifdef VIRTUAL
int nSamples = DEFAULT_NUM_SAMPLES;
#else
int nSamples = 1; int nSamples = 1;
#endif
int detPos[2] = {0, 0}; int detPos[2] = {0, 0};
int isInitCheckDone() { return initCheckDone; } int isInitCheckDone() { return initCheckDone; }
@ -436,23 +431,17 @@ void initControlServer() {
} }
void initStopServer() { void initStopServer() {
if (!updateFlag && initError == OK) {
usleep(CTRL_SRVR_INIT_TIME_US); usleep(CTRL_SRVR_INIT_TIME_US);
LOG(logINFOBLUE, ("Configuring Stop server\n"));
if (mapCSP0() == FAIL) { if (mapCSP0() == FAIL) {
initError = FAIL; LOG(logERROR,
strcpy(initErrorMessage, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"));
"Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); exit(EXIT_FAILURE);
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
return;
} }
#ifdef VIRTUAL #ifdef VIRTUAL
sharedMemory_setStop(0); sharedMemory_setStop(0);
#endif #endif
} }
initCheckDone = 1;
}
/* set up detector */ /* set up detector */
@ -580,7 +569,6 @@ void setupDetector() {
setFrequency(ADC_CLK, DEFAULT_ADC_CLK); setFrequency(ADC_CLK, DEFAULT_ADC_CLK);
setFrequency(DBIT_CLK, DEFAULT_DBIT_CLK); setFrequency(DBIT_CLK, DEFAULT_DBIT_CLK);
setPhase(ADC_CLK, DEFAULT_ADC_PHASE_DEG, 1); setPhase(ADC_CLK, DEFAULT_ADC_PHASE_DEG, 1);
setNextFrameNumber(DEFAULT_STARTING_FRAME_NUMBER);
} }
int updateDatabytesandAllocateRAM() { int updateDatabytesandAllocateRAM() {
@ -712,16 +700,7 @@ void resetPeripheral() {
/* set parameters - dr, adcenablemask */ /* set parameters - dr, adcenablemask */
int setDynamicRange(int dr) { int setDynamicRange(int dr) { return DYNAMIC_RANGE; }
if (dr == 16)
return OK;
return FAIL;
}
int getDynamicRange(int *retval) {
*retval = DYNAMIC_RANGE;
return OK;
}
int setADCEnableMask(uint32_t mask) { int setADCEnableMask(uint32_t mask) {
if (mask == 0u) { if (mask == 0u) {
@ -821,24 +800,6 @@ uint32_t getADCInvertRegister() {
} }
/* parameters - timer */ /* parameters - timer */
int setNextFrameNumber(uint64_t value) {
LOG(logINFO,
("Setting next frame number: %llu\n", (long long unsigned int)value));
setU64BitReg(value, NEXT_FRAME_NUMB_LOCAL_LSB_REG,
NEXT_FRAME_NUMB_LOCAL_MSB_REG);
#ifndef VIRTUAL
// for 1g udp interface
setUDPFrameNumber(value);
#endif
return OK;
}
int getNextFrameNumber(uint64_t *retval) {
*retval = getU64BitReg(NEXT_FRAME_NUMB_LOCAL_LSB_REG,
NEXT_FRAME_NUMB_LOCAL_MSB_REG);
return OK;
}
void setNumFrames(int64_t val) { void setNumFrames(int64_t val) {
if (val > 0) { if (val > 0) {
LOG(logINFO, ("Setting number of frames %lld\n", (long long int)val)); LOG(logINFO, ("Setting number of frames %lld\n", (long long int)val));
@ -1196,8 +1157,6 @@ enum timingMode getTiming() {
/* configure mac */ /* configure mac */
int getNumberofUDPInterfaces() { return 1; }
void calcChecksum(udp_header *udp) { void calcChecksum(udp_header *udp) {
int count = IP_HEADER_SIZE; int count = IP_HEADER_SIZE;
long int sum = 0; long int sum = 0;
@ -1703,14 +1662,11 @@ void *start_timer(void *arg) {
} }
// Send data // Send data
uint64_t frameNr = 0;
getNextFrameNumber(&frameNr);
// loop over number of frames // loop over number of frames
for (int iframes = 0; iframes != numFrames; ++iframes) { for (int frameNr = 0; frameNr != numFrames; ++frameNr) {
// check if manual stop // check if manual stop
if (sharedMemory_getStop() == 1) { if (sharedMemory_getStop() == 1) {
setNextFrameNumber(frameNr + iframes + 1);
break; break;
} }
@ -1728,11 +1684,11 @@ void *start_timer(void *arg) {
sls_detector_header *header = (sls_detector_header *)(packetData); sls_detector_header *header = (sls_detector_header *)(packetData);
header->detType = (uint16_t)myDetectorType; header->detType = (uint16_t)myDetectorType;
header->version = SLS_DETECTOR_HEADER_VERSION - 1; header->version = SLS_DETECTOR_HEADER_VERSION - 1;
header->frameNumber = frameNr + iframes; header->frameNumber = virtual_currentFrameNumber;
header->packetNumber = i; header->packetNumber = i;
header->modId = 0; header->modId = 0;
header->row = detPos[Y]; header->row = detPos[X];
header->column = detPos[X]; header->column = detPos[Y];
// fill data // fill data
memcpy(packetData + sizeof(sls_detector_header), memcpy(packetData + sizeof(sls_detector_header),
@ -1741,18 +1697,19 @@ void *start_timer(void *arg) {
sendUDPPacket(0, 0, packetData, packetSize); sendUDPPacket(0, 0, packetData, packetSize);
} }
LOG(logINFO, ("Sent frame: %d [%lld]\n", iframes, frameNr + iframes)); LOG(logINFO, ("Sent frame: %d [%lld]\n", frameNr,
(long long unsigned int)virtual_currentFrameNumber));
clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_REALTIME, &end);
int64_t timeNs = int64_t timeNs =
((end.tv_sec - begin.tv_sec) * 1E9 + (end.tv_nsec - begin.tv_nsec)); ((end.tv_sec - begin.tv_sec) * 1E9 + (end.tv_nsec - begin.tv_nsec));
// sleep for (period - exptime) // sleep for (period - exptime)
if (iframes < numFrames) { // if there is a next frame if (frameNr < numFrames) { // if there is a next frame
if (periodNs > timeNs) { if (periodNs > timeNs) {
usleep((periodNs - timeNs) / 1000); usleep((periodNs - timeNs) / 1000);
} }
} }
setNextFrameNumber(frameNr + numFrames); ++virtual_currentFrameNumber;
} }
closeUDPSocket(0); closeUDPSocket(0);

View File

@ -79,7 +79,6 @@ enum CLKINDEX { RUN_CLK, ADC_CLK, SYNC_CLK, DBIT_CLK, NUM_CLOCKS };
/** Default Parameters */ /** Default Parameters */
#define DEFAULT_PATTERN_FILE ("DefaultPattern_moench.txt") #define DEFAULT_PATTERN_FILE ("DefaultPattern_moench.txt")
#define DEFAULT_STARTING_FRAME_NUMBER (1)
#define DEFAULT_DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL) #define DEFAULT_DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL)
#define DEFAULT_NUM_SAMPLES (5000) #define DEFAULT_NUM_SAMPLES (5000)
#define DEFAULT_EXPTIME (0) #define DEFAULT_EXPTIME (0)
@ -105,8 +104,6 @@ enum CLKINDEX { RUN_CLK, ADC_CLK, SYNC_CLK, DBIT_CLK, NUM_CLOCKS };
#define DEFAULT_PIPELINE (15) #define DEFAULT_PIPELINE (15)
#define DEFAULT_SETTINGS (G4_HIGHGAIN) #define DEFAULT_SETTINGS (G4_HIGHGAIN)
#define UDP_HEADER_MAX_FRAME_VALUE (0xFFFFFFFFFFFF)
// settings // settings
#define DEFAULT_PATMASK (0x00000C800000800AULL) #define DEFAULT_PATMASK (0x00000C800000800AULL)
#define G1_HIGHGAIN_PATSETBIT (0x00000C0000008008ULL) #define G1_HIGHGAIN_PATSETBIT (0x00000C0000008008ULL)

View File

@ -10,6 +10,20 @@
#include <string.h> #include <string.h>
/*
// Common C/C++ structure to handle pattern data
typedef struct __attribute__((packed)) {
uint64_t word[MAX_PATTERN_LENGTH];
uint64_t ioctrl;
uint32_t limits[2];
// loop0 start, loop0 stop .. loop2 start, loop2 stop
uint32_t loop[6];
uint32_t nloop[3];
uint32_t wait[3];
uint64_t waittime[3];
} patternParameters;
*/
int chipStatusRegister = 0; int chipStatusRegister = 0;
int setBit(int ibit, int patword) { return patword |= (1 << ibit); } int setBit(int ibit, int patword) { return patword |= (1 << ibit); }
@ -18,6 +32,44 @@ int clearBit(int ibit, int patword) { return patword &= ~(1 << ibit); }
int getChipStatusRegister() { return chipStatusRegister; } int getChipStatusRegister() { return chipStatusRegister; }
int gainCapsToCsr(int caps) {
// Translates bit representation
int csr = 0;
if (!(caps & M3_C10pre))
csr |= 1 << _CSR_C10pre;
if (caps & M3_C15sh)
csr |= 1 << CSR_C15sh;
if (caps & M3_C30sh)
csr |= 1 << CSR_C30sh;
if (caps & M3_C50sh)
csr |= 1 << CSR_C50sh;
if (caps & M3_C225ACsh)
csr |= 1 << CSR_C225ACsh;
if (!(caps & M3_C15pre))
csr |= 1 << _CSR_C15pre;
return csr;
}
int csrToGainCaps(int csr) {
// Translates bit representation
int caps = 0;
if (!(csr & (1 << _CSR_C10pre)))
caps |= M3_C10pre;
if (csr & (1 << CSR_C15sh))
caps |= M3_C15sh;
if (csr & (1 << CSR_C30sh))
caps |= M3_C30sh;
if (csr & (1 << CSR_C50sh))
caps |= M3_C50sh;
if (csr & (1 << CSR_C225ACsh))
caps |= M3_C225ACsh;
if (!(csr & (1 << _CSR_C15pre)))
caps |= M3_C15pre;
return caps;
}
patternParameters *setChipStatusRegisterPattern(int csr) { patternParameters *setChipStatusRegisterPattern(int csr) {
int iaddr = 0; int iaddr = 0;
int nbits = 18; int nbits = 18;
@ -97,116 +149,54 @@ patternParameters *setChipStatusRegisterPattern(int csr) {
return pat; return pat;
} }
int getGainCaps() { patternParameters *setInterpolation(int mask) {
int csr = chipStatusRegister; int csr;
// Translates bit representation if (mask)
int caps = 0; csr = chipStatusRegister | (1 << CSR_interp);
if (!(csr & (1 << _CSR_C10pre)))
caps |= M3_C10pre;
if (csr & (1 << CSR_C15sh))
caps |= M3_C15sh;
if (csr & (1 << CSR_C30sh))
caps |= M3_C30sh;
if (csr & (1 << CSR_C50sh))
caps |= M3_C50sh;
if (csr & (1 << CSR_C225ACsh))
caps |= M3_C225ACsh;
if (!(csr & (1 << _CSR_C15pre)))
caps |= M3_C15pre;
return caps;
}
int M3SetGainCaps(int caps) {
int csr = chipStatusRegister & ~GAIN_MASK;
// Translates bit representation
if (!(caps & M3_C10pre))
csr |= 1 << _CSR_C10pre;
if (caps & M3_C15sh)
csr |= 1 << CSR_C15sh;
if (caps & M3_C30sh)
csr |= 1 << CSR_C30sh;
if (caps & M3_C50sh)
csr |= 1 << CSR_C50sh;
if (caps & M3_C225ACsh)
csr |= 1 << CSR_C225ACsh;
if (!(caps & M3_C15pre))
csr |= 1 << _CSR_C15pre;
return csr;
}
int getInterpolation() {
return ((chipStatusRegister & CSR_interp_MSK) >> CSR_interp);
}
int M3SetInterpolation(int enable) {
int csr = 0;
if (enable)
csr = chipStatusRegister | CSR_interp_MSK;
else else
csr = chipStatusRegister & ~CSR_interp_MSK; csr = chipStatusRegister & ~(1 << CSR_interp);
return csr;
return setChipStatusRegisterPattern(csr);
} }
int getPumpProbe() { patternParameters *setPumpProbe(int mask) {
return ((chipStatusRegister & CSR_pumprobe_MSK) >> CSR_pumprobe); int csr;
} if (mask)
csr = chipStatusRegister | (1 << CSR_pumprobe);
int M3SetPumpProbe(int enable) {
LOG(logINFO, ("%s Pump Probe\n", enable == 0 ? "Disabling" : "Enabling"));
int csr = 0;
if (enable)
csr = chipStatusRegister | CSR_pumprobe_MSK;
else else
csr = chipStatusRegister & ~CSR_pumprobe_MSK; csr = chipStatusRegister & ~(1 << CSR_pumprobe);
return csr;
}
int getDigitalPulsing() { return setChipStatusRegisterPattern(csr);
return ((chipStatusRegister & CSR_dpulse_MSK) >> CSR_dpulse);
} }
patternParameters *setDigitalPulsing(int mask) {
int M3SetDigitalPulsing(int enable) { int csr;
LOG(logINFO, if (mask)
("%s Digital Pulsing\n", enable == 0 ? "Disabling" : "Enabling")); csr = chipStatusRegister | (1 << CSR_dpulse);
int csr = 0;
if (enable)
csr = chipStatusRegister | CSR_dpulse_MSK;
else else
csr = chipStatusRegister & ~CSR_dpulse_MSK; csr = chipStatusRegister & ~(1 << CSR_dpulse);
return csr;
}
int getAnalogPulsing() { return setChipStatusRegisterPattern(csr);
return ((chipStatusRegister & CSR_apulse_MSK) >> CSR_apulse);
} }
patternParameters *setAnalogPulsing(int mask) {
int M3SetAnalogPulsing(int enable) { int csr;
LOG(logINFO, if (mask)
("%s Analog Pulsing\n", enable == 0 ? "Disabling" : "Enabling")); csr = chipStatusRegister | (1 << CSR_apulse);
int csr = 0;
if (enable)
csr = chipStatusRegister | CSR_apulse_MSK;
else else
csr = chipStatusRegister & ~CSR_apulse_MSK; csr = chipStatusRegister & ~(1 << CSR_apulse);
return csr;
}
int getNegativePolarity() { return setChipStatusRegisterPattern(csr);
return ((chipStatusRegister & CSR_invpol_MSK) >> CSR_invpol);
} }
patternParameters *setNegativePolarity(int mask) {
int M3SetNegativePolarity(int enable) { int csr;
LOG(logINFO, if (mask)
("%s Negative Polarity\n", enable == 0 ? "Disabling" : "Enabling")); csr = chipStatusRegister | (1 << CSR_invpol);
int csr = 0;
if (enable)
csr = chipStatusRegister | CSR_invpol_MSK;
else else
csr = chipStatusRegister & ~CSR_invpol_MSK; csr = chipStatusRegister & ~(1 << CSR_invpol);
return csr;
return setChipStatusRegisterPattern(csr);
} }
patternParameters *setChannelRegisterChip(int ichip, int *mask, int *trimbits) { patternParameters *setChannelRegisterChip(int ichip, int *mask, int *trimbits) {

View File

@ -49,12 +49,6 @@
// shaper) // shaper)
#define _CSR_C15pre 14 // negative polarity #define _CSR_C15pre 14 // negative polarity
#define CSR_invpol_MSK (0x1 << CSR_invpol)
#define CSR_dpulse_MSK (0x1 << CSR_dpulse)
#define CSR_interp_MSK (0x1 << CSR_interp)
#define CSR_pumprobe_MSK (0x1 << CSR_pumprobe)
#define CSR_apulse_MSK (0x1 << CSR_apulse)
#define CSR_default (1 << _CSR_C10pre) | (1 << CSR_C30sh) #define CSR_default (1 << _CSR_C10pre) | (1 << CSR_C30sh)
#define GAIN_MASK \ #define GAIN_MASK \
@ -64,20 +58,15 @@
int setBit(int ibit, int patword); int setBit(int ibit, int patword);
int clearBit(int ibit, int patword); int clearBit(int ibit, int patword);
int getChipStatusRegister(); int getChipStatusRegister();
int gainCapsToCsr(int caps);
int csrToGainCaps(int csr);
patternParameters *setChipStatusRegisterPattern(int csr); patternParameters *setChipStatusRegisterPattern(int csr);
patternParameters *setChannelRegisterChip(int ichip, int *mask, int *trimbits); patternParameters *setChannelRegisterChip(int ichip, int *mask, int *trimbits);
int getGainCaps(); patternParameters *setInterpolation(int mask);
int M3SetGainCaps(int caps); patternParameters *setPumpProbe(int mask);
int getInterpolation(); patternParameters *setDigitalPulsing(int mask);
int M3SetInterpolation(int enable); patternParameters *setAnalogPulsing(int mask);
int getPumpProbe(); patternParameters *setNegativePolarity(int mask);
int M3SetPumpProbe(int enable);
int getDigitalPulsing();
int M3SetDigitalPulsing(int enable);
int getAnalogPulsing();
int M3SetAnalogPulsing(int enable);
int getNegativePolarity();
int M3SetNegativePolarity(int enable);
#endif #endif

View File

@ -35,9 +35,6 @@ extern int isControlServer;
extern void getMacAddressinString(char *cmac, int size, uint64_t mac); extern void getMacAddressinString(char *cmac, int size, uint64_t mac);
extern void getIpAddressinString(char *cip, uint32_t ip); extern void getIpAddressinString(char *cip, uint32_t ip);
// Variables that will be exported
int masterCommandLine = -1;
int initError = OK; int initError = OK;
int initCheckDone = 0; int initCheckDone = 0;
char initErrorMessage[MAX_STR_LENGTH]; char initErrorMessage[MAX_STR_LENGTH];
@ -45,7 +42,6 @@ char initErrorMessage[MAX_STR_LENGTH];
#ifdef VIRTUAL #ifdef VIRTUAL
pthread_t pthread_virtual_tid; pthread_t pthread_virtual_tid;
int64_t virtual_currentFrameNumber = 2; int64_t virtual_currentFrameNumber = 2;
int virtual_moduleid = 0;
#endif #endif
enum detectorSettings thisSettings = UNINITIALIZED; enum detectorSettings thisSettings = UNINITIALIZED;
@ -292,18 +288,6 @@ void setModuleId(int modid) {
bus_r(MOD_ID_REG) | ((modid << MOD_ID_OFST) & MOD_ID_MSK)); bus_r(MOD_ID_REG) | ((modid << MOD_ID_OFST) & MOD_ID_MSK));
} }
int updateModuleId() {
int modid = getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
if (initError == FAIL) {
return FAIL;
}
#ifdef VIRTUAL
virtual_moduleid = modid;
#endif
setModuleId(modid);
return OK;
}
u_int64_t getDetectorMAC() { u_int64_t getDetectorMAC() {
#ifdef VIRTUAL #ifdef VIRTUAL
return 0; return 0;
@ -367,27 +351,17 @@ void initControlServer() {
} }
void initStopServer() { void initStopServer() {
if (!updateFlag && initError == OK) {
usleep(CTRL_SRVR_INIT_TIME_US); usleep(CTRL_SRVR_INIT_TIME_US);
LOG(logINFOBLUE, ("Configuring Stop server\n"));
if (mapCSP0() == FAIL) { if (mapCSP0() == FAIL) {
initError = FAIL; LOG(logERROR,
strcpy(initErrorMessage, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"));
"Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); exit(EXIT_FAILURE);
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
return;
} }
#ifdef VIRTUAL #ifdef VIRTUAL
sharedMemory_setStop(0); sharedMemory_setStop(0);
if (checkCommandLineConfiguration() == FAIL) {
initCheckDone = 1;
return;
}
#endif #endif
} }
initCheckDone = 1;
}
/* set up detector */ /* set up detector */
@ -432,12 +406,6 @@ void setupDetector() {
allocateDetectorStructureMemory(); allocateDetectorStructureMemory();
if (checkCommandLineConfiguration() == FAIL)
return;
if (updateModuleId() == FAIL)
return;
clkDivider[READOUT_C0] = DEFAULT_READOUT_C0; clkDivider[READOUT_C0] = DEFAULT_READOUT_C0;
clkDivider[READOUT_C1] = DEFAULT_READOUT_C1; clkDivider[READOUT_C1] = DEFAULT_READOUT_C1;
clkDivider[SYSTEM_C0] = DEFAULT_SYSTEM_C0; clkDivider[SYSTEM_C0] = DEFAULT_SYSTEM_C0;
@ -478,6 +446,13 @@ void setupDetector() {
setASICDefaults(); setASICDefaults();
setADIFDefaults(); setADIFDefaults();
// set module id in register
int modid = getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
if (initError == FAIL) {
return;
}
setModuleId(modid);
// set trigger flow for m3 (for all timing modes) // set trigger flow for m3 (for all timing modes)
bus_w(FLOW_TRIGGER_REG, bus_r(FLOW_TRIGGER_REG) | FLOW_TRIGGER_MSK); bus_w(FLOW_TRIGGER_REG, bus_r(FLOW_TRIGGER_REG) | FLOW_TRIGGER_MSK);
@ -501,6 +476,13 @@ void setupDetector() {
setInitialExtSignals(); setInitialExtSignals();
// 10G UDP // 10G UDP
enableTenGigabitEthernet(1); enableTenGigabitEthernet(1);
#ifdef VIRTUAL
enableTenGigabitEthernet(0);
#endif
getModuleIdInFile(&initError, initErrorMessage, ID_FILE);
if (initError == FAIL) {
return;
}
setSettings(DEFAULT_SETTINGS); setSettings(DEFAULT_SETTINGS);
// check module type attached if not in debug mode // check module type attached if not in debug mode
@ -717,27 +699,6 @@ void setADIFDefaults() {
ADIF_ADDTNL_OFST_MSK))); ADIF_ADDTNL_OFST_MSK)));
} }
int checkCommandLineConfiguration() {
if (masterCommandLine != -1) {
#ifdef VIRTUAL
if (masterCommandLine == 1) {
bus_w(SYSTEM_STATUS_REG,
bus_r(SYSTEM_STATUS_REG) & ~SYSTEM_STATUS_SLV_BRD_DTCT_MSK);
} else {
bus_w(SYSTEM_STATUS_REG,
bus_r(SYSTEM_STATUS_REG) | SYSTEM_STATUS_SLV_BRD_DTCT_MSK);
}
#else
initError = FAIL;
strcpy(initErrorMessage,
"Cannot set Master from command line for this detector. "
"Should have been caught before!\n");
return FAIL;
#endif
}
return OK;
}
/* firmware functions (resets) */ /* firmware functions (resets) */
void cleanFifos() { void cleanFifos() {
@ -767,9 +728,7 @@ void resetPeripheral() {
/* set parameters - dr, roi */ /* set parameters - dr, roi */
int setDynamicRange(int dr) { int setDynamicRange(int dr) {
if (dr <= 0) { if (dr > 0) {
return FAIL;
}
uint32_t regval = 0; uint32_t regval = 0;
switch (dr) { switch (dr) {
/*case 1: TODO:Not implemented in firmware yet /*case 1: TODO:Not implemented in firmware yet
@ -792,29 +751,23 @@ int setDynamicRange(int dr) {
bus_w(CONFIG_REG, bus_r(CONFIG_REG) & ~CONFIG_DYNAMIC_RANGE_MSK); bus_w(CONFIG_REG, bus_r(CONFIG_REG) & ~CONFIG_DYNAMIC_RANGE_MSK);
bus_w(CONFIG_REG, bus_r(CONFIG_REG) | regval); bus_w(CONFIG_REG, bus_r(CONFIG_REG) | regval);
updatePacketizing(); updatePacketizing();
return OK;
} }
int getDynamicRange(int *retval) {
uint32_t regval = bus_r(CONFIG_REG) & CONFIG_DYNAMIC_RANGE_MSK; uint32_t regval = bus_r(CONFIG_REG) & CONFIG_DYNAMIC_RANGE_MSK;
switch (regval) { switch (regval) {
/*case CONFIG_DYNAMIC_RANGE_1_VAL: TODO:Not implemented in firmware yet /*case CONFIG_DYNAMIC_RANGE_1_VAL: TODO:Not implemented in firmware yet
return 1;*/ return 1;*/
case CONFIG_DYNAMIC_RANGE_8_VAL: case CONFIG_DYNAMIC_RANGE_8_VAL:
*retval = 8; return 8;
break;
case CONFIG_DYNAMIC_RANGE_16_VAL: case CONFIG_DYNAMIC_RANGE_16_VAL:
*retval = 16; return 16;
break;
case CONFIG_DYNAMIC_RANGE_24_VAL: case CONFIG_DYNAMIC_RANGE_24_VAL:
*retval = 32; return 32;
break;
default: default:
LOG(logERROR, ("Invalid dynamic range %d read back\n", LOG(logERROR, ("Invalid dynamic range %d read back\n",
regval >> CONFIG_DYNAMIC_RANGE_OFST)); regval >> CONFIG_DYNAMIC_RANGE_OFST));
return FAIL; return -1;
} }
return OK;
} }
/* set parameters - readout */ /* set parameters - readout */
@ -1137,8 +1090,7 @@ void updatePacketizing() {
// 10g // 10g
if (tgEnable) { if (tgEnable) {
int dr = 0; const int dr = setDynamicRange(-1);
getDynamicRange(&dr);
packetsPerFrame = 1; packetsPerFrame = 1;
if (dr == 32 && ncounters > 1) { if (dr == 32 && ncounters > 1) {
packetsPerFrame = 2; packetsPerFrame = 2;
@ -1592,18 +1544,14 @@ int setHighVoltage(int val) {
/* parameters - timing */ /* parameters - timing */
int isMaster(int *retval) { int isMaster() {
int slave = ((bus_r(SYSTEM_STATUS_REG) & SYSTEM_STATUS_SLV_BRD_DTCT_MSK) >> return !((bus_r(SYSTEM_STATUS_REG) & SYSTEM_STATUS_SLV_BRD_DTCT_MSK) >>
SYSTEM_STATUS_SLV_BRD_DTCT_OFST); SYSTEM_STATUS_SLV_BRD_DTCT_OFST);
*retval = (slave == 0 ? 1 : 0);
return OK;
} }
void setTiming(enum timingMode arg) { void setTiming(enum timingMode arg) {
int master = 0; if (!isMaster() && arg == AUTO_TIMING)
isMaster(&master);
if (!master && arg == AUTO_TIMING)
arg = TRIGGER_EXPOSURE; arg = TRIGGER_EXPOSURE;
uint32_t addr = CONFIG_REG; uint32_t addr = CONFIG_REG;
@ -1689,55 +1637,6 @@ void setInitialExtSignals() {
DOUTIF_RISING_LNGTH_PORT_1_MSK)); DOUTIF_RISING_LNGTH_PORT_1_MSK));
} }
int setGainCaps(int caps) {
LOG(logINFO, ("Setting gain caps to: %u\n", caps));
int csr = M3SetGainCaps(caps);
return setChipStatusRegister(csr);
}
int setInterpolation(int enable) {
LOG(logINFO,
("%s Interpolation\n", enable == 0 ? "Disabling" : "Enabling"));
if (enable) {
setCounterMask(MAX_COUNTER_MSK);
if (getCounterMask() != MAX_COUNTER_MSK) {
LOG(logERROR,
("Could not set interpolation. Could not enable all counters"));
return FAIL;
}
LOG(logINFO, ("\tEnabled all counters\n"));
}
int csr = M3SetInterpolation(enable);
return setChipStatusRegister(csr);
}
int setPumpProbe(int enable) {
LOG(logINFO, ("%s Pump Probe\n", enable == 0 ? "Disabling" : "Enabling"));
int csr = M3SetPumpProbe(enable);
return setChipStatusRegister(csr);
}
int setDigitalPulsing(int enable) {
LOG(logINFO,
("%s Digital Pulsing\n", enable == 0 ? "Disabling" : "Enabling"));
int csr = M3SetDigitalPulsing(enable);
return setChipStatusRegister(csr);
}
int setAnalogPulsing(int enable) {
LOG(logINFO,
("%s Analog Pulsing\n", enable == 0 ? "Disabling" : "Enabling"));
int csr = M3SetAnalogPulsing(enable);
return setChipStatusRegister(csr);
}
int setNegativePolarity(int enable) {
LOG(logINFO,
("%s Negative Polarity\n", enable == 0 ? "Disabling" : "Enabling"));
int csr = M3SetNegativePolarity(enable);
return setChipStatusRegister(csr);
}
void setExtSignal(int signalIndex, enum externalSignalFlag mode) { void setExtSignal(int signalIndex, enum externalSignalFlag mode) {
LOG(logDEBUG1, ("Setting signal flag[%d] to %d\n", signalIndex, mode)); LOG(logDEBUG1, ("Setting signal flag[%d] to %d\n", signalIndex, mode));
@ -1820,8 +1719,6 @@ int getExtSignal(int signalIndex) {
} }
} }
int getNumberofUDPInterfaces() { return 1; }
int configureMAC() { int configureMAC() {
uint32_t srcip = udpDetails[0].srcip; uint32_t srcip = udpDetails[0].srcip;
@ -1941,7 +1838,7 @@ int setDetectorPosition(int pos[]) {
int ret = OK; int ret = OK;
// row // row
value = detPos[Y]; value = detPos[X];
bus_w(addr, (bus_r(addr) & ~COORD_ROW_MSK) | bus_w(addr, (bus_r(addr) & ~COORD_ROW_MSK) |
((value << COORD_ROW_OFST) & COORD_ROW_MSK)); ((value << COORD_ROW_OFST) & COORD_ROW_MSK));
valueRead = ((bus_r(addr) & COORD_ROW_MSK) >> COORD_ROW_OFST); valueRead = ((bus_r(addr) & COORD_ROW_MSK) >> COORD_ROW_OFST);
@ -1952,7 +1849,7 @@ int setDetectorPosition(int pos[]) {
} }
// col // col
value = detPos[X]; value = detPos[Y];
bus_w(addr, (bus_r(addr) & ~COORD_COL_MSK) | bus_w(addr, (bus_r(addr) & ~COORD_COL_MSK) |
((value << COORD_COL_OFST) & COORD_COL_MSK)); ((value << COORD_COL_OFST) & COORD_COL_MSK));
valueRead = ((bus_r(addr) & COORD_COL_MSK) >> COORD_COL_OFST); valueRead = ((bus_r(addr) & COORD_COL_MSK) >> COORD_COL_OFST);
@ -1963,8 +1860,7 @@ int setDetectorPosition(int pos[]) {
} }
if (ret == OK) { if (ret == OK) {
LOG(logINFO, LOG(logINFO, ("\tPosition set to [%d, %d]\n", detPos[X], detPos[Y]));
("\tPosition set to [%d, %d] #(col, row)\n", detPos[X], detPos[Y]));
} }
return ret; return ret;
@ -2303,8 +2199,7 @@ void *start_timer(void *arg) {
const int imageSize = calculateDataBytes(); const int imageSize = calculateDataBytes();
const int tgEnable = enableTenGigabitEthernet(-1); const int tgEnable = enableTenGigabitEthernet(-1);
int dr = 0; const int dr = setDynamicRange(-1);
getDynamicRange(&dr);
int ncounters = __builtin_popcount(getCounterMask()); int ncounters = __builtin_popcount(getCounterMask());
int dataSize = 0; int dataSize = 0;
int packetsPerFrame = 0; int packetsPerFrame = 0;
@ -2385,9 +2280,9 @@ void *start_timer(void *arg) {
header->version = SLS_DETECTOR_HEADER_VERSION - 1; header->version = SLS_DETECTOR_HEADER_VERSION - 1;
header->frameNumber = virtual_currentFrameNumber; header->frameNumber = virtual_currentFrameNumber;
header->packetNumber = i; header->packetNumber = i;
header->modId = virtual_moduleid; header->modId = 0;
header->row = detPos[Y]; header->row = detPos[X];
header->column = detPos[X]; header->column = detPos[Y];
// fill data // fill data
memcpy(packetData + sizeof(sls_detector_header), memcpy(packetData + sizeof(sls_detector_header),
@ -2625,8 +2520,7 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) {
int calculateDataBytes() { int calculateDataBytes() {
int numCounters = __builtin_popcount(getCounterMask()); int numCounters = __builtin_popcount(getCounterMask());
int dr = 0; int dr = setDynamicRange(-1);
getDynamicRange(&dr);
return (NCHAN_1_COUNTER * NCHIP * numCounters * ((double)dr / 8.00)); return (NCHAN_1_COUNTER * NCHIP * numCounters * ((double)dr / 8.00));
} }
@ -2673,3 +2567,21 @@ int setChipStatusRegister(int csr) {
return iret; return iret;
} }
int setGainCaps(int caps) {
LOG(logINFO, ("Setting gain caps to: %u\n", caps));
// Update only gain caps, leave the rest of the CSR unchanged
int csr = getChipStatusRegister();
csr &= ~GAIN_MASK;
caps = gainCapsToCsr(caps);
// caps &= GAIN_MASK;
csr |= caps;
return setChipStatusRegister(csr);
}
int getGainCaps() {
int csr = getChipStatusRegister();
int caps = csrToGainCaps(csr);
return caps;
}

View File

@ -95,7 +95,7 @@ enum DACINDEX {
#define DAC_NAMES \ #define DAC_NAMES \
"vcassh", "vth2", "vrshaper", "vrshaper_n", "vipre_out", "vth3", "vth1", \ "vcassh", "vth2", "vrshaper", "vrshaper_n", "vipre_out", "vth3", "vth1", \
"vicin", "vcas", "vrpreamp", "vcal_n", "vipre", "vishaper", "vcal_p", \ "vicin", "vcas", "vrpreamp", "vcal_n", "vipre", "vishaper", "vcal_p", \
"vtrim", "vdcsh", "vthreshold" "vtrim", "vdcsh"
#define DEFAULT_DAC_VALS \ #define DEFAULT_DAC_VALS \
{ \ { \
1200, /* casSh */ \ 1200, /* casSh */ \

View File

@ -4,11 +4,25 @@
#include <inttypes.h> #include <inttypes.h>
uint32_t getUDPPacketNumber();
uint64_t getUDPFrameNumber();
void setUDPFrameNumber(uint64_t fnum);
/** /**
* Get current udp packet number
*/
uint32_t getUDPPacketNumber();
/**
* Get current udp frame number
*/
uint64_t getUDPFrameNumber();
/**
* Called for each UDP packet header creation
* @param buffer pointer to header
* @param id module id * @param id module id
*/ */
void createUDPPacketHeader(char *buffer, uint16_t id); void createUDPPacketHeader(char *buffer, uint16_t id);
/**
* fill up the udp packet with data till its full
* @param buffer pointer to memory
*/
int fillUDPPacket(char *buffer); int fillUDPPacket(char *buffer);

View File

@ -66,5 +66,3 @@ int moveBinaryFile(char *mess, char *dest, char *src, char *errorPrefix);
int createEmptyFile(char *mess, char *fname, char *errorPrefix); int createEmptyFile(char *mess, char *fname, char *errorPrefix);
int deleteFile(char *mess, char *fname, char *errorPrefix); int deleteFile(char *mess, char *fname, char *errorPrefix);
int deleteOldServers(char *mess, char *newServerPath, char *errorPrefix);

View File

@ -26,12 +26,10 @@ int preparetoCopyProgram(char *mess, char *functionType, FILE **fd,
uint64_t fsize); uint64_t fsize);
int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index, int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index,
char *functionType, char *clientChecksum, char *functionType, char *clientChecksum,
ssize_t fsize, int forceDeleteNormalFile); ssize_t fsize);
int getDrive(char *mess, enum PROGRAM_INDEX index); int getDrive(char *mess, enum PROGRAM_INDEX index);
/** Notify fpga not to touch flash, open src and flash drive to write */ /** Notify fpga not to touch flash, open src and flash drive to write */
int openFileForFlash(char *mess, enum PROGRAM_INDEX index, FILE **flashfd, FILE **srcfd, int openFileForFlash(char *mess, FILE **flashfd, FILE **srcfd);
int forceDeleteNormalFile);
int checkNormalFile(char *mess, enum PROGRAM_INDEX index, int forceDeleteNormalFile);
int eraseFlash(char *mess); int eraseFlash(char *mess);
/* write from tmp file to flash */ /* write from tmp file to flash */
int writeToFlash(char *mess, ssize_t fsize, FILE *flashfd, FILE *srcfd); int writeToFlash(char *mess, ssize_t fsize, FILE *flashfd, FILE *srcfd);

View File

@ -97,9 +97,6 @@ u_int32_t getDetectorNumber();
#if defined(GOTTHARD2D) || defined(EIGERD) || defined(MYTHEN3D) #if defined(GOTTHARD2D) || defined(EIGERD) || defined(MYTHEN3D)
int getModuleId(int *ret, char *mess); int getModuleId(int *ret, char *mess);
#endif #endif
#if defined(EIGERD) || defined(MYTHEN3D) || defined(GOTTHARD2D)
int updateModuleId();
#endif
#if defined(GOTTHARD2D) || defined(MYTHEN3D) #if defined(GOTTHARD2D) || defined(MYTHEN3D)
void setModuleId(int modid); void setModuleId(int modid);
#endif #endif
@ -113,11 +110,7 @@ u_int32_t getBoardRevision();
void initControlServer(); void initControlServer();
void initStopServer(); void initStopServer();
#ifdef EIGERD #ifdef EIGERD
int updateModuleConfiguration(); void getModuleConfiguration();
int getModuleConfiguration(int *m, int *t, int *n);
#ifdef VIRTUAL
void checkVirtual9MFlag();
#endif
#endif #endif
// set up detector // set up detector
@ -144,10 +137,6 @@ void setADIFDefaults();
#if defined(GOTTHARD2D) || defined(EIGERD) || defined(JUNGFRAUD) #if defined(GOTTHARD2D) || defined(EIGERD) || defined(JUNGFRAUD)
int readConfigFile(); int readConfigFile();
#endif #endif
#if defined(GOTTHARDD) || defined(GOTTHARD2D) || defined(EIGERD) || \
defined(MYTHEN3D)
int checkCommandLineConfiguration();
#endif
#ifdef EIGERD #ifdef EIGERD
void resetToHardwareSettings(); void resetToHardwareSettings();
#endif #endif
@ -184,7 +173,6 @@ void setMasterSlaveConfiguration();
// parameters - dr, roi // parameters - dr, roi
int setDynamicRange(int dr); int setDynamicRange(int dr);
int getDynamicRange(int *retval);
#ifdef GOTTHARDD #ifdef GOTTHARDD
int setROI(ROI arg); int setROI(ROI arg);
ROI getROI(); ROI getROI();
@ -225,8 +213,7 @@ int getReadoutMode();
int selectStoragecellStart(int pos); int selectStoragecellStart(int pos);
int getMaxStoragecellStart(); int getMaxStoragecellStart();
#endif #endif
#if defined(JUNGFRAUD) || defined(EIGERD) || defined(MOENCHD) || \ #if defined(JUNGFRAUD) || defined(EIGERD)
defined(CHIPTESTBOARDD)
int setNextFrameNumber(uint64_t value); int setNextFrameNumber(uint64_t value);
int getNextFrameNumber(uint64_t *value); int getNextFrameNumber(uint64_t *value);
#endif #endif
@ -374,16 +361,9 @@ int getADC(enum ADCINDEX ind);
int setHighVoltage(int val); int setHighVoltage(int val);
// parameters - timing, extsig // parameters - timing, extsig
#ifdef EIGERD #if defined(MYTHEN3D) || defined(EIGERD) || defined(GOTTHARDD)
int setMaster(enum MASTERINDEX m); int isMaster();
int setTop(enum TOPINDEX t);
int isTop(int *retval);
#endif #endif
#if defined(MYTHEN3D) || defined(EIGERD) || defined(GOTTHARDD) || \
defined(GOTTHARD2D)
int isMaster(int *retval);
#endif
#ifdef GOTTHARD2D #ifdef GOTTHARD2D
void updatingRegisters(); void updatingRegisters();
#endif #endif
@ -391,13 +371,9 @@ void setTiming(enum timingMode arg);
enum timingMode getTiming(); enum timingMode getTiming();
#ifdef MYTHEN3D #ifdef MYTHEN3D
void setInitialExtSignals(); void setInitialExtSignals();
int setChipStatusRegister(int csr);
int setGainCaps(int caps); int setGainCaps(int caps);
int setInterpolation(int enable); int getGainCaps();
int setPumpProbe(int enable); int setChipStatusRegister(int csr);
int setDigitalPulsing(int enable);
int setAnalogPulsing(int enable);
int setNegativePolarity(int enable);
int setDACS(int *dacs); int setDACS(int *dacs);
#endif #endif
#if defined(GOTTHARDD) || defined(MYTHEN3D) #if defined(GOTTHARDD) || defined(MYTHEN3D)
@ -411,8 +387,8 @@ void calcChecksum(mac_conf *mac, int sourceip, int destip);
#endif #endif
#if defined(JUNGFRAUD) || defined(GOTTHARD2D) #if defined(JUNGFRAUD) || defined(GOTTHARD2D)
void setNumberofUDPInterfaces(int val); void setNumberofUDPInterfaces(int val);
#endif
int getNumberofUDPInterfaces(); int getNumberofUDPInterfaces();
#endif
#if defined(JUNGFRAUD) || defined(EIGERD) #if defined(JUNGFRAUD) || defined(EIGERD)
int getNumberofDestinations(int *retval); int getNumberofDestinations(int *retval);

View File

@ -132,6 +132,7 @@ int check_version(int);
int software_trigger(int); int software_trigger(int);
int led(int); int led(int);
int digital_io_delay(int); int digital_io_delay(int);
int copy_detector_server(int);
int reboot_controller(int); int reboot_controller(int);
int set_adc_enable_mask(int); int set_adc_enable_mask(int);
int get_adc_enable_mask(int); int get_adc_enable_mask(int);
@ -244,7 +245,6 @@ int get_pattern(int);
int load_default_pattern(int); int load_default_pattern(int);
int get_all_threshold_energy(int); int get_all_threshold_energy(int);
int get_master(int); int get_master(int);
int set_master(int);
int get_csr(); int get_csr();
int set_gain_caps(int); int set_gain_caps(int);
int get_gain_caps(int); int get_gain_caps(int);
@ -284,22 +284,9 @@ int update_detector_server(int);
int receive_program(int file_des, enum PROGRAM_INDEX index); int receive_program(int file_des, enum PROGRAM_INDEX index);
void receive_program_via_blackfin(int file_des, enum PROGRAM_INDEX index, void receive_program_via_blackfin(int file_des, enum PROGRAM_INDEX index,
char *functionType, uint64_t filesize, char *functionType, uint64_t filesize,
char *checksum, char *serverName, char *checksum, char *serverName);
int forceDeleteNormalFile);
void receive_program_default(int file_des, enum PROGRAM_INDEX index, void receive_program_default(int file_des, enum PROGRAM_INDEX index,
char *functionType, uint64_t filesize, char *functionType, uint64_t filesize,
char *checksum, char *serverName); char *checksum, char *serverName);
int get_update_mode(int); int get_update_mode(int);
int set_update_mode(int); int set_update_mode(int);
int get_top(int);
int set_top(int);
int get_polarity(int);
int set_polarity(int);
int get_interpolation(int);
int set_interpolation(int);
int get_pump_probe(int);
int set_pump_probe(int);
int get_analog_pulsing(int);
int set_analog_pulsing(int);
int get_digital_pulsing(int);
int set_digital_pulsing(int);

View File

@ -32,11 +32,6 @@ uint64_t udpFrameNumber = 0;
uint32_t getUDPPacketNumber() { return udpPacketNumber; } uint32_t getUDPPacketNumber() { return udpPacketNumber; }
uint64_t getUDPFrameNumber() { return udpFrameNumber; } uint64_t getUDPFrameNumber() { return udpFrameNumber; }
void setUDPFrameNumber(uint64_t fnum) {
LOG(logINFO, ("Setting next frame number also for 1g to %lld\n", fnum));
// this gets incremented before setting it
udpFrameNumber = fnum - 1;
}
void createUDPPacketHeader(char *buffer, uint16_t id) { void createUDPPacketHeader(char *buffer, uint16_t id) {
memset(buffer, 0, sizeof(sls_detector_header)); memset(buffer, 0, sizeof(sls_detector_header));

View File

@ -50,10 +50,6 @@ int ConvertToDifferentRange(int inputMin, int inputMax, int outputMin,
} }
int getAbsPath(char *buf, size_t bufSize, char *fname) { int getAbsPath(char *buf, size_t bufSize, char *fname) {
if (fname[0] == '/') {
strcpy(buf, fname);
return OK;
}
// get path of current binary // get path of current binary
char path[bufSize]; char path[bufSize];
memset(path, 0, bufSize); memset(path, 0, bufSize);
@ -64,14 +60,10 @@ int getAbsPath(char *buf, size_t bufSize, char *fname) {
} }
path[len] = '\0'; path[len] = '\0';
// get dir path and attach file name // get dir path and attach config file name
char *dir = dirname(path); char *dir = dirname(path);
memset(buf, 0, bufSize); memset(buf, 0, bufSize);
if (!strcmp(dir, "/")) {
sprintf(buf, "/%s", fname);
} else {
sprintf(buf, "%s/%s", dir, fname); sprintf(buf, "%s/%s", dir, fname);
}
LOG(logDEBUG1, ("full path for %s: %s\n", fname, buf)); LOG(logDEBUG1, ("full path for %s: %s\n", fname, buf));
return OK; return OK;
} }
@ -82,14 +74,8 @@ int getTimeFromString(char *buf, time_t *result) {
// remove timezone as strptime cannot validate timezone despite // remove timezone as strptime cannot validate timezone despite
// documentation (for blackfin) // documentation (for blackfin)
LOG(logDEBUG, ("kernel v %s\n", buffer)); LOG(logDEBUG, ("kernel v %s\n", buffer));
char timezone[8] = {0}; const char *timezone = {"CEST"};
strcpy(timezone, "CEST");
char *res = strstr(buffer, timezone); char *res = strstr(buffer, timezone);
// remove CET as well
if (res == NULL) {
strcpy(timezone, "CET");
res = strstr(buffer, timezone);
}
if (res != NULL) { if (res != NULL) {
size_t cestPos = res - buffer; size_t cestPos = res - buffer;
size_t pos = cestPos + strlen(timezone) + 1; size_t pos = cestPos + strlen(timezone) + 1;
@ -474,7 +460,7 @@ int setupDetectorServer(char *mess, char *sname) {
LOG(logERROR, (mess)); LOG(logERROR, (mess));
return FAIL; return FAIL;
} }
LOG(logINFO, ("\tSymbolic link created %s -> %s\n", linkname, sname)); LOG(logINFO, ("\tSymbolic link created\n"));
// blackfin boards (respawn) (only kept for backwards compatibility) // blackfin boards (respawn) (only kept for backwards compatibility)
#ifndef VIRTUAL #ifndef VIRTUAL
@ -493,7 +479,7 @@ int setupDetectorServer(char *mess, char *sname) {
// add new link name to /etc/inittab // add new link name to /etc/inittab
if (snprintf(cmd, MAX_STR_LENGTH, if (snprintf(cmd, MAX_STR_LENGTH,
"echo 'ttyS0::respawn:%s' >> /etc/inittab", "echo 'ttyS0::respawn:/./%s' >> /etc/inittab",
linkname) >= MAX_STR_LENGTH) { linkname) >= MAX_STR_LENGTH) {
strcpy(mess, "Could not copy detector server. Command " strcpy(mess, "Could not copy detector server. Command "
"to add new server for spawning is too long\n"); "to add new server for spawning is too long\n");
@ -678,26 +664,3 @@ int deleteFile(char *mess, char *fname, char *errorPrefix) {
} }
return OK; return OK;
} }
int deleteOldServers(char *mess, char *newServerPath, char *errorPrefix) {
LOG(logINFO, ("\tChecking if current binary is to be deleted ...\n"))
// get path of current binary (get file name if link)
char currentBinary[MAX_STR_LENGTH];
memset(currentBinary, 0, MAX_STR_LENGTH);
ssize_t len = readlink("/proc/self/exe", currentBinary, MAX_STR_LENGTH - 1);
if (len < 0) {
LOG(logWARNING, ("(%s): Could not delete old servers. Could not "
"readlink current binary\n",
errorPrefix));
return FAIL;
}
currentBinary[len] = '\0';
LOG(logDEBUG1, ("Current binary:%s\n", currentBinary));
// delete file
if (deleteFile(mess, currentBinary, errorPrefix) == FAIL) {
LOG(logWARNING, ("(%s). Could not delete old servers\n", errorPrefix));
return FAIL;
}
return OK;
}

View File

@ -7,7 +7,6 @@
#include "slsDetectorServer_defs.h" #include "slsDetectorServer_defs.h"
#include <string.h> #include <string.h>
#include <sys/stat.h>
#include <sys/sysinfo.h> #include <sys/sysinfo.h>
#include <unistd.h> // usleep #include <unistd.h> // usleep
@ -39,9 +38,6 @@
#define CMD_GET_AMD_FLASH "dmesg | grep Amd" #define CMD_GET_AMD_FLASH "dmesg | grep Amd"
#define CMD_CREATE_DEVICE_FILE_PART1 "mknod"
#define CMD_CREATE_DEVICE_FILE_PART2 "c 90 6"
#define FLASH_BUFFER_MEMORY_SIZE (128 * 1024) // 500 KB #define FLASH_BUFFER_MEMORY_SIZE (128 * 1024) // 500 KB
// clang-format on // clang-format on
@ -278,8 +274,7 @@ int allowUpdate(char *mess, char *functionType) {
getKernelVersion(retvals); getKernelVersion(retvals);
snprintf(mess, MAX_STR_LENGTH, snprintf(mess, MAX_STR_LENGTH,
"Could not update %s. Kernel version %s is too old to " "Could not update %s. Kernel version %s is too old to "
"update the Amd flash/ root directory. Most likely, blackfin " "update the Amd flash/ root directory. Most likely, blackfin needs rescue or replacement. Please contact us.\n",
"needs rescue or replacement. Please contact us.\n",
functionType, retvals); functionType, retvals);
LOG(logERROR, (mess)); LOG(logERROR, (mess));
return FAIL; return FAIL;
@ -324,7 +319,7 @@ int preparetoCopyProgram(char *mess, char *functionType, FILE **fd,
int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index, int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index,
char *functionType, char *clientChecksum, char *functionType, char *clientChecksum,
ssize_t fsize, int forceDeleteNormalFile) { ssize_t fsize) {
memset(messageType, 0, sizeof(messageType)); memset(messageType, 0, sizeof(messageType));
strcpy(messageType, functionType); strcpy(messageType, functionType);
@ -335,8 +330,7 @@ int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index,
FILE *flashfd = NULL; FILE *flashfd = NULL;
FILE *srcfd = NULL; FILE *srcfd = NULL;
if (openFileForFlash(mess, index, &flashfd, &srcfd, forceDeleteNormalFile) == if (openFileForFlash(mess, &flashfd, &srcfd) == FAIL) {
FAIL) {
return FAIL; return FAIL;
} }
@ -440,8 +434,7 @@ int getDrive(char *mess, enum PROGRAM_INDEX index) {
return OK; return OK;
} }
int openFileForFlash(char *mess, enum PROGRAM_INDEX index, FILE **flashfd, FILE **srcfd, int openFileForFlash(char *mess, FILE **flashfd, FILE **srcfd) {
int forceDeleteNormalFile) {
// open src file // open src file
*srcfd = fopen(TEMP_PROG_FILE_NAME, "r"); *srcfd = fopen(TEMP_PROG_FILE_NAME, "r");
if (*srcfd == NULL) { if (*srcfd == NULL) {
@ -454,11 +447,6 @@ int openFileForFlash(char *mess, enum PROGRAM_INDEX index, FILE **flashfd, FILE
} }
LOG(logDEBUG1, ("Temp file ready for reading\n")); LOG(logDEBUG1, ("Temp file ready for reading\n"));
if (checkNormalFile(mess, index, forceDeleteNormalFile) == FAIL) {
fclose(*srcfd);
return FAIL;
}
// open flash drive for writing // open flash drive for writing
*flashfd = fopen(flashDriveName, "w"); *flashfd = fopen(flashDriveName, "w");
if (*flashfd == NULL) { if (*flashfd == NULL) {
@ -474,95 +462,6 @@ int openFileForFlash(char *mess, enum PROGRAM_INDEX index, FILE **flashfd, FILE
return OK; return OK;
} }
int checkNormalFile(char *mess, enum PROGRAM_INDEX index, int forceDeleteNormalFile) {
#ifndef VIRTUAL
// check if its a normal file or special file
struct stat buf;
if (stat(flashDriveName, &buf) == -1) {
sprintf(mess,
"Could not %s. Unable to find the flash drive %s\n",
messageType, flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
// zero = normal file (not char special drive file)
if (!S_ISCHR(buf.st_mode)) {
// kernel memory is not permanent
if (index != PROGRAM_FPGA) {
sprintf(mess,
"Could not %s. The flash drive found is a normal file. "
"Reboot board using 'rebootcontroller' command to load "
"proper device tree\n",
messageType);
LOG(logERROR, (mess));
return FAIL;
}
// user does not allow to fix it (default)
if (forceDeleteNormalFile == 0) {
sprintf(mess,
"Could not %s. The flash drive %s found for fpga programming is a normal file. To "
"fix this (by deleting this file, creating the flash drive and proceeding with "
"programming), re-run the programming command 'programfpga' with parameter "
"'--force-delete-normal-file'\n",
messageType, flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
// fpga memory stays after a reboot, user allowed to fix it
LOG(logWARNING, ("Flash drive invalidated (normal file). Fixing it...\n"));
// user allows to fix it, so force delete normal file
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
if (snprintf(cmd, MAX_STR_LENGTH, "rm %s", flashDriveName) >=
MAX_STR_LENGTH) {
sprintf(mess,
"Could not update %s. Command to delete normal file %s is "
"too long\n",
messageType, flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(
mess, MAX_STR_LENGTH,
"Could not update %s. (could not delete normal file %s: %s)\n",
messageType, flashDriveName, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tDeleted Normal File (%s)\n", flashDriveName));
// create special drive
if (snprintf(cmd, MAX_STR_LENGTH, "%s %s %s",
CMD_CREATE_DEVICE_FILE_PART1, flashDriveName,
CMD_CREATE_DEVICE_FILE_PART2) >= MAX_STR_LENGTH) {
sprintf(mess,
"Could not update %s. Command to create special file %s is "
"too long\n",
messageType, flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(
mess, MAX_STR_LENGTH,
"Could not update %s. (could not create special file %s: %s)\n",
messageType, flashDriveName, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tSpecial File created (%s)\n", flashDriveName));
} else {
LOG(logINFO, ("\tValidated flash drive (not a normal file)\n"));
}
#endif
return OK;
}
int eraseFlash(char *mess) { int eraseFlash(char *mess) {
LOG(logINFO, ("\tErasing Flash...\n")); LOG(logINFO, ("\tErasing Flash...\n"));

View File

@ -8,7 +8,6 @@
#include <string.h> #include <string.h>
#include <unistd.h> // usleep #include <unistd.h> // usleep
#include <sys/stat.h>
/* global variables */ /* global variables */
@ -147,30 +146,6 @@ int getDrive(char *mess, enum PROGRAM_INDEX index) {
} }
int openFileForFlash(char *mess, FILE **flashfd) { int openFileForFlash(char *mess, FILE **flashfd) {
#ifndef VIRTUAL
// check if its a normal file or special file
struct stat buf;
if (stat(flashDriveName, &buf) == -1) {
sprintf(mess,
"Could not %s. Unable to find the flash drive %s\n",
messageType, flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
// zero = normal file (not char drive special file)
if (!S_ISCHR(buf.st_mode)) {
// memory is not permanent
sprintf(mess,
"Could not %s. The flash drive found is a normal file. "
"Reboot board using 'rebootcontroller' command to load "
"proper device tree\n",
messageType);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tValidated flash drive (not a normal file)\n"));
#endif
*flashfd = fopen(flashDriveName, "w"); *flashfd = fopen(flashDriveName, "w");
if (*flashfd == NULL) { if (*flashfd == NULL) {
sprintf(mess, sprintf(mess,

Some files were not shown because too many files have changed in this diff Show More