merging problem

This commit is contained in:
bergamaschi 2020-02-18 10:55:41 +01:00
commit fc27cfd663
138 changed files with 2252 additions and 1698 deletions

1
.gitignore vendored
View File

@ -7,6 +7,7 @@ bin/
*.out *.out
*.toc *.toc
*.o *.o
*.so
.* .*
build build
RELEASE.txt RELEASE.txt

View File

@ -4,39 +4,25 @@ language: cpp
os: linux os: linux
env: dist: bionic
matrix:
- CONDA_PY=3.6
- CONDA_PY=3.7
- CONDA_PY=3.8
dist: trusty
install: install:
- sudo apt-get update - sudo apt-get update
- ldd --version - ldd --version
- wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh; - wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;
- bash miniconda.sh -b -p $HOME/miniconda - bash miniconda.sh -b -p $HOME/miniconda
- export PATH="$HOME/miniconda/bin:$PATH" - source "$HOME/miniconda/etc/profile.d/conda.sh"
- rm -f miniconda.sh - rm -f miniconda.sh
- hash -r - hash -r
- conda config --set always_yes yes --set changeps1 no - conda config --set always_yes yes --set changeps1 no
- conda config --add channels conda-forge - conda config --add channels conda-forge
- conda config --add channels slsdetectorgroup - conda config --add channels slsdetectorgroup
- conda update conda - conda update -q conda
- conda update --all
- conda install conda-build=3.17
- conda install anaconda-client
- conda install conda-verify
# Useful for debugging any issues with conda
- conda info -a - conda info -a
# Useful for debugging any issues with conda
# Replace dep1 dep2 ... with your dependencies - conda create -q -n testenv conda-build anaconda-client conda-verify
- conda create -q -n test-environment python=$CONDA_PY - conda activate testenv
- source activate test-environment
- conda-build . - conda-build .
script: script:
@ -45,7 +31,7 @@ script:
deploy: deploy:
provider: script provider: script
script: find $HOME/miniconda/conda-bld/${TRAVIS_OS_NAME}-64 -name "*.tar.bz2" -exec anaconda -t $CONDA_TOKEN upload --force {} \; script: find $HOME/miniconda/envs/testenv/conda-bld/${TRAVIS_OS_NAME}-64 -name "*.tar.bz2" -exec anaconda -t $CONDA_TOKEN upload --force {} \;
on: on:
branch: developer branch: developer

View File

@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.11) cmake_minimum_required(VERSION 3.12)
project(slsDetectorPackage) project(slsDetectorPackage)
set(PROJECT_VERSION 5.0.0) set(PROJECT_VERSION 5.0.0)
include(CheckIPOSupported) include(CheckIPOSupported)
@ -126,7 +126,7 @@ install(TARGETS slsProjectOptions slsProjectWarnings rapidjson
) )
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 TRUE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
@ -174,6 +174,7 @@ if (SLS_USE_INTEGRATION_TESTS)
endif (SLS_USE_INTEGRATION_TESTS) endif (SLS_USE_INTEGRATION_TESTS)
if (SLS_USE_PYTHON) if (SLS_USE_PYTHON)
set(PYBIND11_CPP_STANDARD -std=c++11)
add_subdirectory(libs/pybind11) add_subdirectory(libs/pybind11)
add_subdirectory(python) add_subdirectory(python)
endif(SLS_USE_PYTHON) endif(SLS_USE_PYTHON)

View File

@ -0,0 +1,2 @@
Draft
- dr 4, 8, 16 in eiger -> speed 0, 32 stays same (speed 1)

View File

@ -1,3 +1,4 @@
mkdir build mkdir build
mkdir install mkdir install
cd build cd build
@ -6,7 +7,7 @@ cmake .. \
-DCMAKE_INSTALL_PREFIX=install \ -DCMAKE_INSTALL_PREFIX=install \
-DSLS_USE_TEXTCLIENT=ON \ -DSLS_USE_TEXTCLIENT=ON \
-DSLS_USE_RECEIVER=ON \ -DSLS_USE_RECEIVER=ON \
-DSLS_USE_GUI=OFF \ -DSLS_USE_GUI=ON \
-DSLS_USE_TESTS=ON \ -DSLS_USE_TESTS=ON \
-DSLS_USE_PYTHON=OFF \ -DSLS_USE_PYTHON=OFF \
-DCMAKE_BUILD_TYPE=Release \ -DCMAKE_BUILD_TYPE=Release \

View File

@ -1,14 +1,4 @@
# mkdir $PREFIX/lib echo "|<-------- starting python build"
# mkdir $PREFIX/include
# #Shared and static libraries
# cp build/bin/_sls_detector* $PREFIX/lib/.
# #Binaries
# cp -r build/bin/sls_detector $PREFIX/lib/.
cd python cd python
${PYTHON} setup.py install ${PYTHON} setup.py install

View File

@ -0,0 +1,7 @@
python:
- 3.6
- 3.7
- 3.8
numpy:
- 1.17

View File

@ -0,0 +1,9 @@
mkdir $PREFIX/lib
mkdir $PREFIX/bin
mkdir $PREFIX/include
cp build/bin/ctbGui $PREFIX/bin/.
cp build/bin/libctbRootLib.so $PREFIX/lib/.

View File

@ -1,15 +1,3 @@
#Copy the GUI
mkdir $PREFIX/lib
mkdir $PREFIX/bin mkdir $PREFIX/bin
mkdir $PREFIX/include
#No libs for gui?
#Binaries
cp build/bin/gui_client $PREFIX/bin/.
cp build/bin/slsDetectorGui $PREFIX/bin/. cp build/bin/slsDetectorGui $PREFIX/bin/.
#Which headers do we need for development??
# cp include/some_lib.h $PREFIX/include/.

View File

@ -8,6 +8,7 @@ source:
build: build:
number: 1 number: 1
binary_relocation: True
rpaths: rpaths:
- lib/ - lib/
@ -16,10 +17,9 @@ requirements:
- {{ compiler('c') }} - {{ compiler('c') }}
- {{compiler('cxx')}} - {{compiler('cxx')}}
- cmake - cmake
# - qwt 6.* #require qt5 investigate befor activating gui - qwt 6.*
# - qt=4.8.7=7 - qt 4.8.*
- zeromq=4.2.5=hfc679d8_5 - zeromq
- pyzmq
- xorg-libx11 - xorg-libx11
- xorg-libice - xorg-libice
- xorg-libxext - xorg-libxext
@ -51,70 +51,46 @@ requirements:
outputs: outputs:
- name: sls_detector_lib - name: slsdetlib
script: copy_lib.sh script: copy_lib.sh
- name: sls_detector requirements:
run:
- libstdcxx-ng
- libgcc-ng
- zeromq
- name: slsdet
script: build_pylib.sh script: build_pylib.sh
requirements: requirements:
build: build:
- python
- {{ compiler('c') }} - {{ compiler('c') }}
- {{compiler('cxx')}} - {{compiler('cxx')}}
- python {{ python }} - {{ pin_subpackage('slsdetlib', exact=True) }}
- setuptools - setuptools
- sls_detector_lib
- pyzmq
- pybind11 2.4
host: host:
- python - python
- pybind11 2.4
- pyzmq run:
- sls_detector_lib
- libstdcxx-ng - libstdcxx-ng
- libgcc-ng - libgcc-ng
run:
- python - python
- numpy - numpy
- sls_detector_lib=developer - {{ pin_subpackage('slsdetlib', exact=True) }}
- pyzmq
- libstdcxx-ng
- libgcc-ng
test: test:
imports: imports:
- sls_detector - slsdet
# requirements: - name: slsdetgui
# build: script: copy_gui.sh
# - {{ compiler('c') }} requirements:
# - {{compiler('cxx')}} run:
- {{ pin_subpackage('slsdetlib', exact=True) }}
# - name: sls_detector_gui - qwt 6.*
# version: "refactor" - qt 4.8.*
# script: copy_gui.sh
# requirements:
# build:
# - {{ compiler('c') }}
# - {{compiler('cxx')}}
# - cmake
# - qwt 6.*
# - qt=4.8.7=7
# - zeromq=4.2.5=hfc679d8_5
# - pyzmq
# - xorg-libx11
# - xorg-libice
# - xorg-libxext
# - xorg-libsm
# - xorg-libxau
# - xorg-libxrender
# - xorg-libxfixes
# - {{ cdt('mesa-libgl-devel') }} # [linux]
# - {{ cdt('mesa-libegl-devel') }} # [linux]
# - {{ cdt('mesa-dri-drivers') }} # [linux]
# - {{ cdt('libselinux') }} # [linux]
# - {{ cdt('libxdamage') }} # [linux]
# - {{ cdt('libxxf86vm') }} # [linux]
# run:
# - sls_detector_lib=refactor
# - qwt 6.*
# - qt=4.8.7=7

View File

@ -71,6 +71,11 @@ target_link_libraries(ctbRootLib PUBLIC
${ROOT_EXE_LINKER_FLAGS} ${ROOT_EXE_LINKER_FLAGS}
) )
set_target_properties(
ctbRootLib PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
target_link_libraries(ctbGui PUBLIC target_link_libraries(ctbGui PUBLIC
slsDetectorShared slsDetectorShared
slsSupportLib slsSupportLib
@ -80,4 +85,5 @@ target_link_libraries(ctbGui PUBLIC
set_target_properties(ctbGui PROPERTIES set_target_properties(ctbGui PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
) )

View File

@ -12,7 +12,7 @@ file writing etc.
.. code-block:: python .. code-block:: python
from sls_detector import Eiger from slsdet import Eiger
d = Eiger() d = Eiger()
threshold = range(0, 2000, 200) threshold = range(0, 2000, 200)

View File

@ -1,12 +1,12 @@
#include "catch.hpp" #include "catch.hpp"
#include "multiSlsDetector.h" #include "DetectorImpl.h"
#include "string_utils.h" #include "string_utils.h"
#include "tests/globals.h" #include "tests/globals.h"
#include <iostream> #include <iostream>
class MultiDetectorFixture { class MultiDetectorFixture {
protected: protected:
multiSlsDetector d; DetectorImpl d;
public: public:
MultiDetectorFixture() : d(0, true, true) { MultiDetectorFixture() : d(0, true, true) {

View File

@ -3,7 +3,7 @@
#include "ClientSocket.h" #include "ClientSocket.h"
#include "logger.h" #include "logger.h"
#include "multiSlsDetector.h" #include "DetectorImpl.h"
#include "slsDetector.h" #include "slsDetector.h"
#include "sls_detector_defs.h" #include "sls_detector_defs.h"
@ -252,7 +252,7 @@ TEST_CASE(
int ratecorr = 125; int ratecorr = 125;
// pick up multi detector from shm id 0 // pick up multi detector from shm id 0
multiSlsDetector m(0); DetectorImpl m(0);
// ensure eiger detector type, hostname and online // ensure eiger detector type, hostname and online
REQUIRE(m.getDetectorTypeAsEnum() == c.type_enum); REQUIRE(m.getDetectorTypeAsEnum() == c.type_enum);
@ -302,7 +302,7 @@ TEST_CASE("Chiptestboard Loading Patterns", "[.ctbintegration]") {
SingleDetectorConfig c; SingleDetectorConfig c;
// pick up multi detector from shm id 0 // pick up multi detector from shm id 0
multiSlsDetector m(0); DetectorImpl m(0);
// ensure ctb detector type, hostname and online // ensure ctb detector type, hostname and online
REQUIRE(m.getDetectorTypeAsEnum() == c.type_enum); REQUIRE(m.getDetectorTypeAsEnum() == c.type_enum);
@ -387,7 +387,7 @@ TEST_CASE("Chiptestboard Dbit offset, list, sampling, advinvert", "[.ctbintegrat
SingleDetectorConfig c; SingleDetectorConfig c;
// pick up multi detector from shm id 0 // pick up multi detector from shm id 0
multiSlsDetector m(0); DetectorImpl m(0);
// ensure ctb detector type, hostname and online // ensure ctb detector type, hostname and online
REQUIRE(m.getDetectorTypeAsEnum() == c.type_enum); REQUIRE(m.getDetectorTypeAsEnum() == c.type_enum);
@ -457,7 +457,7 @@ TEST_CASE("Eiger or Jungfrau startingfnum", "[.eigerintegration][.jungfrauintegr
SingleDetectorConfig c; SingleDetectorConfig c;
// pick up multi detector from shm id 0 // pick up multi detector from shm id 0
multiSlsDetector m(0); DetectorImpl m(0);
// ensure ctb detector type, hostname and online // ensure ctb detector type, hostname and online
REQUIRE(((m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::EIGER) || (m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::JUNGFRAU))); REQUIRE(((m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::EIGER) || (m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::JUNGFRAU)));
@ -495,7 +495,7 @@ TEST_CASE("Eiger readnlines", "[.eigerintegration][readnlines]") {
SingleDetectorConfig c; SingleDetectorConfig c;
// pick up multi detector from shm id 0 // pick up multi detector from shm id 0
multiSlsDetector m(0); DetectorImpl m(0);
// ensure detector type, hostname // ensure detector type, hostname
REQUIRE((m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::EIGER)); REQUIRE((m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::EIGER));

View File

@ -1,5 +1,5 @@
#include "catch.hpp" #include "catch.hpp"
#include "multiSlsDetector.h" #include "DetectorImpl.h"
#include "string_utils.h" #include "string_utils.h"
#include "tests/globals.h" #include "tests/globals.h"
#include <iostream> #include <iostream>
@ -9,7 +9,7 @@ using namespace Catch::literals;
TEST_CASE("Initialize a multi detector", "[.integration][.multi]") { TEST_CASE("Initialize a multi detector", "[.integration][.multi]") {
auto hostnames = sls::split(test::hostname, '+'); auto hostnames = sls::split(test::hostname, '+');
multiSlsDetector d(0, true, true); DetectorImpl d(0, true, true);
d.setHostname(test::hostname.c_str()); d.setHostname(test::hostname.c_str());
CHECK(d.getHostname() == test::hostname); CHECK(d.getHostname() == test::hostname);
@ -28,7 +28,7 @@ TEST_CASE("Initialize a multi detector", "[.integration][.multi]") {
TEST_CASE("Set and read timers", "[.integration][.multi]") { TEST_CASE("Set and read timers", "[.integration][.multi]") {
multiSlsDetector d(0, true, true); DetectorImpl d(0, true, true);
d.setHostname(test::hostname.c_str()); d.setHostname(test::hostname.c_str());
// FRAME_NUMBER // FRAME_NUMBER

@ -1 +1 @@
Subproject commit 80d452484c5409444b0ec19383faa84bb7a4d351 Subproject commit 4f72ef846fe8453596230ac285eeaa0ce3278bb4

View File

@ -1,20 +1,22 @@
pybind11_add_module(_sls_detector # find_package (Python COMPONENTS Interpreter Development)
pybind11_add_module(_slsdet
src/main.cpp src/main.cpp
src/enums.cpp src/enums.cpp
src/detector.cpp src/detector.cpp
src/network.cpp src/network.cpp
) )
target_link_libraries(_sls_detector PUBLIC target_link_libraries(_slsdet PUBLIC
slsDetectorShared slsDetectorShared
slsReceiverShared slsReceiverShared
slsSupportLib slsSupportLib
zmq ) )
set_target_properties(_sls_detector PROPERTIES set_target_properties(_slsdet PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
) )
@ -38,8 +40,8 @@ set( PYTHON_FILES
) )
foreach(FILE ${PYTHON_FILES}) foreach(FILE ${PYTHON_FILES})
configure_file( sls_detector/${FILE} configure_file( slsdet/${FILE}
${CMAKE_BINARY_DIR}/bin/sls_detector/${FILE} ) ${CMAKE_BINARY_DIR}/bin/slsdet/${FILE} )
endforeach(FILE ${PYTHON_FILES}) endforeach(FILE ${PYTHON_FILES})

View File

@ -8,7 +8,7 @@ import sys
import setuptools import setuptools
import os import os
__version__ = 'refactor' __version__ = 'udp'
def get_conda_path(): def get_conda_path():
@ -19,31 +19,32 @@ def get_conda_path():
return os.environ['CONDA_PREFIX'] return os.environ['CONDA_PREFIX']
class get_pybind_include(object): # class get_pybind_include(object):
"""Helper class to determine the pybind11 include path # """Helper class to determine the pybind11 include path
The purpose of this class is to postpone importing pybind11 # The purpose of this class is to postpone importing pybind11
until it is actually installed, so that the ``get_include()`` # until it is actually installed, so that the ``get_include()``
method can be invoked. """ # method can be invoked. """
def __init__(self, user=False): # def __init__(self, user=False):
self.user = user # self.user = user
def __str__(self): # def __str__(self):
import pybind11 # import pybind11
return pybind11.get_include(self.user) # return pybind11.get_include(self.user)
ext_modules = [ ext_modules = [
Extension( Extension(
'_sls_detector', '_slsdet',
['src/main.cpp', ['src/main.cpp',
'src/enums.cpp', 'src/enums.cpp',
'src/detector.cpp', 'src/detector.cpp',
'src/network.cpp'], 'src/network.cpp'],
include_dirs=[ include_dirs=[
# Path to pybind11 headers # Path to pybind11 headers
get_pybind_include(), # get_pybind_include(),
get_pybind_include(user=True), # get_pybind_include(user=True),
os.path.join('../libs/pybind11/include'),
os.path.join(get_conda_path(), 'include/slsDetectorPackage'), os.path.join(get_conda_path(), 'include/slsDetectorPackage'),
], ],
@ -109,20 +110,28 @@ class BuildExt(build_ext):
opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version()) opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version())
for ext in self.extensions: for ext in self.extensions:
ext.extra_compile_args = opts ext.extra_compile_args = opts
print('**************************************************')
print(ct)
print(opts)
print('**************************************************')
build_ext.build_extensions(self) build_ext.build_extensions(self)
def get_shared_lib():
return [f for f in os.listdir('.') if '_slsdet' in f]
setup( setup(
name='sls_detector', name='slsdet',
version=__version__, version=__version__,
author='Erik Frojdh', author='Erik Frojdh',
author_email='erik.frojdh@psi.ch', author_email='erik.frojdh@psi.ch',
url='https://github.com/slsdetectorgroup/sls_detector', url='https://github.com/slsdetectorgroup/slsDetectorPackage',
description='Detector API for SLS Detector Group detectors', description='Detector API for SLS Detector Group detectors',
long_description='', long_description='',
packages=find_packages(exclude=['contrib', 'docs', 'tests']), packages=find_packages(exclude=['contrib', 'docs', 'tests']),
ext_modules=ext_modules, ext_modules=ext_modules,
install_requires=['pybind11>=2.2'],
cmdclass={'build_ext': BuildExt}, cmdclass={'build_ext': BuildExt},
zip_safe=False, zip_safe=False,
) )

View File

@ -1,23 +0,0 @@
# from .detector import Detector, DetectorError, free_shared_memory
from .eiger import Eiger
from .ctb import Ctb
from .dacs import DetectorDacs, Dac
from .detector import Detector
from .jungfrau import Jungfrau
from .mythen3 import Mythen3
# from .jungfrau_ctb import JungfrauCTB
# from _sls_detector import DetectorApi
import _sls_detector
defs = _sls_detector.slsDetectorDefs
runStatus = _sls_detector.slsDetectorDefs.runStatus
speedLevel = _sls_detector.slsDetectorDefs.speedLevel
timingMode = _sls_detector.slsDetectorDefs.timingMode
dacIndex = _sls_detector.slsDetectorDefs.dacIndex
detectorType = _sls_detector.slsDetectorDefs.detectorType
detectorSettings = _sls_detector.slsDetectorDefs.detectorSettings
readoutMode = _sls_detector.slsDetectorDefs.readoutMode
IpAddr = _sls_detector.IpAddr
MacAddr = _sls_detector.MacAddr

23
python/slsdet/__init__.py Executable file
View File

@ -0,0 +1,23 @@
# from .detector import Detector, DetectorError, free_shared_memory
from .eiger import Eiger
from .ctb import Ctb
from .dacs import DetectorDacs, Dac
from .detector import Detector
from .jungfrau import Jungfrau
from .mythen3 import Mythen3
# from .jungfrau_ctb import JungfrauCTB
# from _slsdet import DetectorApi
import _slsdet
defs = _slsdet.slsDetectorDefs
runStatus = _slsdet.slsDetectorDefs.runStatus
speedLevel = _slsdet.slsDetectorDefs.speedLevel
timingMode = _slsdet.slsDetectorDefs.timingMode
dacIndex = _slsdet.slsDetectorDefs.dacIndex
detectorType = _slsdet.slsDetectorDefs.detectorType
detectorSettings = _slsdet.slsDetectorDefs.detectorSettings
readoutMode = _slsdet.slsDetectorDefs.readoutMode
IpAddr = _slsdet.IpAddr
MacAddr = _slsdet.MacAddr

View File

@ -1,8 +1,8 @@
from .detector import Detector from .detector import Detector
from .utils import element_if_equal from .utils import element_if_equal
from .dacs import DetectorDacs from .dacs import DetectorDacs
import _sls_detector import _slsdet
dacIndex = _sls_detector.slsDetectorDefs.dacIndex dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty from .detector_property import DetectorProperty
class CtbDacs(DetectorDacs): class CtbDacs(DetectorDacs):

View File

@ -1,9 +1,9 @@
from .detector_property import DetectorProperty from .detector_property import DetectorProperty
from functools import partial from functools import partial
import numpy as np import numpy as np
import _sls_detector import _slsdet
from .detector import freeze from .detector import freeze
dacIndex = _sls_detector.slsDetectorDefs.dacIndex dacIndex = _slsdet.slsDetectorDefs.dacIndex
class Dac(DetectorProperty): class Dac(DetectorProperty):
""" """
This class represents a dac on the detector. One instance handles all This class represents a dac on the detector. One instance handles all

View File

@ -1,5 +1,5 @@
from _sls_detector import CppDetectorApi from _slsdet import CppDetectorApi
from _sls_detector import slsDetectorDefs from _slsdet import slsDetectorDefs
runStatus = slsDetectorDefs.runStatus runStatus = slsDetectorDefs.runStatus
speedLevel = slsDetectorDefs.speedLevel speedLevel = slsDetectorDefs.speedLevel

View File

@ -11,8 +11,8 @@ from .detector import Detector
# from .adcs import Adc, DetectorAdcs # from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs from .dacs import DetectorDacs
import _sls_detector import _slsdet
dacIndex = _sls_detector.slsDetectorDefs.dacIndex dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty from .detector_property import DetectorProperty
# from .utils import element_if_equal # from .utils import element_if_equal
# from sls_detector.errors import DetectorValueError, DetectorError # from sls_detector.errors import DetectorValueError, DetectorError

View File

@ -9,8 +9,8 @@ from .detector import Detector, freeze
# from .adcs import Adc, DetectorAdcs # from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs from .dacs import DetectorDacs
import _sls_detector import _slsdet
dacIndex = _sls_detector.slsDetectorDefs.dacIndex dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty from .detector_property import DetectorProperty
# @freeze # @freeze

View File

@ -9,8 +9,8 @@ from .detector import Detector, freeze
# from .adcs import Adc, DetectorAdcs # from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs from .dacs import DetectorDacs
import _sls_detector import _slsdet
dacIndex = _sls_detector.slsDetectorDefs.dacIndex dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty from .detector_property import DetectorProperty
# vcassh 1200, # vcassh 1200,

View File

@ -5,7 +5,7 @@ but not directly used in controlling the detector
from collections import namedtuple from collections import namedtuple
import _sls_detector #C++ lib import _slsdet #C++ lib
import functools import functools
@ -29,7 +29,7 @@ def list_to_bitmask(values):
return mask return mask
def to_geo(value): def to_geo(value):
if isinstance(value, _sls_detector.xy): if isinstance(value, _slsdet.xy):
return Geometry(x = value.x, y = value.y) return Geometry(x = value.x, y = value.y)
else: else:
raise ValueError("Can only convert sls_detector.xy") raise ValueError("Can only convert sls_detector.xy")

View File

@ -2,7 +2,7 @@ C++ API
===================================================== =====================================================
.. py:currentmodule:: _sls_detector .. py:currentmodule:: _slsdet
.. autoclass:: DetectorApi .. autoclass:: DetectorApi
:members: :members:

View File

@ -2,7 +2,7 @@ sls_detector - Python interface for the slsDetectorsPackage
============================================================== ==============================================================
sls_detector provide Python bindings to the slsDetectorsPackage using mainly the sls_detector provide Python bindings to the slsDetectorsPackage using mainly the
multiSlsDetector API. This module contains two parts, a compiled C module to DetectorImpl API. This module contains two parts, a compiled C module to
expose the API and a Python class to offer a more Pythonic interface. expose the API and a Python class to offer a more Pythonic interface.

View File

@ -610,6 +610,8 @@ void init_det(py::module &m) {
py::arg() = Positions{}) py::arg() = Positions{})
.def("writeAdcRegister", &Detector::writeAdcRegister, py::arg(), .def("writeAdcRegister", &Detector::writeAdcRegister, py::arg(),
py::arg(), py::arg() = Positions{}) py::arg(), py::arg() = Positions{})
.def("getInitialChecks", &Detector::getInitialChecks)
.def("setInitialChecks", &Detector::setInitialChecks, py::arg())
.def("getControlPort", &Detector::getControlPort, .def("getControlPort", &Detector::getControlPort,
py::arg() = Positions{}) py::arg() = Positions{})
.def("setControlPort", &Detector::setControlPort, py::arg(), .def("setControlPort", &Detector::setControlPort, py::arg(),

View File

@ -19,7 +19,7 @@ void init_enums(py::module &);
void init_experimental(py::module &); void init_experimental(py::module &);
void init_det(py::module &); void init_det(py::module &);
void init_network(py::module &); void init_network(py::module &);
PYBIND11_MODULE(_sls_detector, m) { PYBIND11_MODULE(_slsdet, m) {
m.doc() = R"pbdoc( m.doc() = R"pbdoc(
C/C++ API C/C++ API
----------------------- -----------------------

View File

@ -16,12 +16,12 @@ def d():
def test_acq_call(d, mocker): def test_acq_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.acq') m = mocker.patch('_slsdet.DetectorApi.acq')
d.acq() d.acq()
m.assert_called_once_with() m.assert_called_once_with()
def test_busy_call(d, mocker): def test_busy_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getAcquiringFlag') m = mocker.patch('_slsdet.DetectorApi.getAcquiringFlag')
m.return_value = False m.return_value = False
assert d.busy == False assert d.busy == False
@ -31,103 +31,103 @@ def test_assign_to_detector_type(d):
d.detector_type = 'Eiger' d.detector_type = 'Eiger'
def test_det_type(d, mocker): def test_det_type(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDetectorType') m = mocker.patch('_slsdet.DetectorApi.getDetectorType')
m.return_value = 'Eiger' m.return_value = 'Eiger'
assert d.detector_type == 'Eiger' assert d.detector_type == 'Eiger'
def test_set_dynamic_range_4(d, mocker): def test_set_dynamic_range_4(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') m = mocker.patch('_slsdet.DetectorApi.setDynamicRange')
d.dynamic_range = 4 d.dynamic_range = 4
m.assert_called_with(4) m.assert_called_with(4)
def test_set_dynamic_range_8(d, mocker): def test_set_dynamic_range_8(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') m = mocker.patch('_slsdet.DetectorApi.setDynamicRange')
d.dynamic_range = 8 d.dynamic_range = 8
m.assert_called_with(8) m.assert_called_with(8)
def test_set_dynamic_range_16(d, mocker): def test_set_dynamic_range_16(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') m = mocker.patch('_slsdet.DetectorApi.setDynamicRange')
d.dynamic_range = 16 d.dynamic_range = 16
m.assert_called_with(16) m.assert_called_with(16)
def test_set_dynamic_range_32(d, mocker): def test_set_dynamic_range_32(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') m = mocker.patch('_slsdet.DetectorApi.setDynamicRange')
d.dynamic_range = 32 d.dynamic_range = 32
m.assert_called_with(32) m.assert_called_with(32)
def test_set_dynamic_range_raises_exception(d, mocker): def test_set_dynamic_range_raises_exception(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setDynamicRange') mocker.patch('_slsdet.DetectorApi.setDynamicRange')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.dynamic_range = 17 d.dynamic_range = 17
def test_get_dynamic_range_32(d, mocker): def test_get_dynamic_range_32(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDynamicRange') m = mocker.patch('_slsdet.DetectorApi.getDynamicRange')
m.return_value = 32 m.return_value = 32
dr = d.dynamic_range dr = d.dynamic_range
assert dr == 32 assert dr == 32
def test_eiger_matrix_reset(d, mocker): def test_eiger_matrix_reset(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getCounterBit') m = mocker.patch('_slsdet.DetectorApi.getCounterBit')
m.return_value = True m.return_value = True
assert d.eiger_matrix_reset == True assert d.eiger_matrix_reset == True
def test_set_eiger_matrix_reset(d, mocker): def test_set_eiger_matrix_reset(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setCounterBit') m = mocker.patch('_slsdet.DetectorApi.setCounterBit')
d.eiger_matrix_reset = True d.eiger_matrix_reset = True
m.assert_called_once_with(True) m.assert_called_once_with(True)
def test_get_exposure_time(d, mocker): def test_get_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getExposureTime') m = mocker.patch('_slsdet.DetectorApi.getExposureTime')
m.return_value = 100000000 m.return_value = 100000000
assert d.exposure_time == 0.1 assert d.exposure_time == 0.1
def test_set_exposure_time(d, mocker): def test_set_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setExposureTime') m = mocker.patch('_slsdet.DetectorApi.setExposureTime')
d.exposure_time = 1.5 d.exposure_time = 1.5
m.assert_called_once_with(1500000000) m.assert_called_once_with(1500000000)
def test_set_exposure_time_less_than_zero(d, mocker): def test_set_exposure_time_less_than_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setExposureTime') mocker.patch('_slsdet.DetectorApi.setExposureTime')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.exposure_time = -7 d.exposure_time = -7
def test_get_file_index(d, mocker): def test_get_file_index(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFileIndex') m = mocker.patch('_slsdet.DetectorApi.getFileIndex')
m.return_value = 8 m.return_value = 8
assert d.file_index == 8 assert d.file_index == 8
def test_set_file_index(d, mocker): def test_set_file_index(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFileIndex') m = mocker.patch('_slsdet.DetectorApi.setFileIndex')
d.file_index = 9 d.file_index = 9
m.assert_called_with(9) m.assert_called_with(9)
def test_set_file_index_raises_on_neg(d, mocker): def test_set_file_index_raises_on_neg(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setFileIndex') mocker.patch('_slsdet.DetectorApi.setFileIndex')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.file_index = -9 d.file_index = -9
def test_get_file_name(d, mocker): def test_get_file_name(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFileName') m = mocker.patch('_slsdet.DetectorApi.getFileName')
d.file_name d.file_name
m.assert_called_once_with() m.assert_called_once_with()
def test_set_file_name(d, mocker): def test_set_file_name(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFileName') m = mocker.patch('_slsdet.DetectorApi.setFileName')
d.file_name = 'hej' d.file_name = 'hej'
m.assert_called_once_with('hej') m.assert_called_once_with('hej')
def test_get_file_path(d, mocker): def test_get_file_path(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFilePath') m = mocker.patch('_slsdet.DetectorApi.getFilePath')
d.file_path d.file_path
m.assert_called_once_with() m.assert_called_once_with()
def test_set_file_path_when_path_exists(d, mocker): def test_set_file_path_when_path_exists(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFilePath') m = mocker.patch('_slsdet.DetectorApi.setFilePath')
#To avoid raising an exception because path is not there #To avoid raising an exception because path is not there
mock_os = mocker.patch('os.path.exists') mock_os = mocker.patch('os.path.exists')
mock_os.return_value = True mock_os.return_value = True
@ -135,25 +135,25 @@ def test_set_file_path_when_path_exists(d, mocker):
m.assert_called_once_with('/path/to/something/') m.assert_called_once_with('/path/to/something/')
def test_set_file_path_raises_when_not_exists(d, mocker): def test_set_file_path_raises_when_not_exists(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setFilePath') mocker.patch('_slsdet.DetectorApi.setFilePath')
mock_os = mocker.patch('os.path.exists') mock_os = mocker.patch('os.path.exists')
mock_os.return_value = False mock_os.return_value = False
with pytest.raises(FileNotFoundError): with pytest.raises(FileNotFoundError):
d.file_path = '/path/to/something/' d.file_path = '/path/to/something/'
def test_get_file_write(d, mocker): def test_get_file_write(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFileWrite') m = mocker.patch('_slsdet.DetectorApi.getFileWrite')
m.return_value = False m.return_value = False
assert d.file_write == False assert d.file_write == False
def test_set_file_write(d, mocker): def test_set_file_write(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFileWrite') m = mocker.patch('_slsdet.DetectorApi.setFileWrite')
d.file_write = True d.file_write = True
m.assert_called_once_with(True) m.assert_called_once_with(True)
def test_get_firmware_version(d, mocker): def test_get_firmware_version(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFirmwareVersion') m = mocker.patch('_slsdet.DetectorApi.getFirmwareVersion')
m.return_value = 20 m.return_value = 20
assert d.firmware_version == 20 assert d.firmware_version == 20
@ -162,38 +162,38 @@ def test_cannot_set_fw_version(d):
d.firmware_version = 20 d.firmware_version = 20
def test_get_high_voltage_call_signature(d, mocker): def test_get_high_voltage_call_signature(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDac') m = mocker.patch('_slsdet.DetectorApi.getDac')
d.high_voltage d.high_voltage
m.assert_called_once_with('vhighvoltage', -1) m.assert_called_once_with('vhighvoltage', -1)
def test_get_high_voltage(d, mocker): def test_get_high_voltage(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDac') m = mocker.patch('_slsdet.DetectorApi.getDac')
m.return_value = 80 m.return_value = 80
assert d.high_voltage == 80 assert d.high_voltage == 80
#self._api.setDac('vhighvoltage', -1, voltage) #self._api.setDac('vhighvoltage', -1, voltage)
def test_set_high_voltage(d, mocker): def test_set_high_voltage(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDac') m = mocker.patch('_slsdet.DetectorApi.setDac')
d.high_voltage = 80 d.high_voltage = 80
m.assert_called_once_with('vhighvoltage', -1, 80) m.assert_called_once_with('vhighvoltage', -1, 80)
def test_decode_hostname_two_names(d, mocker): def test_decode_hostname_two_names(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getHostname') m = mocker.patch('_slsdet.DetectorApi.getHostname')
m.return_value = 'beb059+beb048+' m.return_value = 'beb059+beb048+'
assert d.hostname == ['beb059', 'beb048'] assert d.hostname == ['beb059', 'beb048']
def test_decode_hostname_four_names(d, mocker): def test_decode_hostname_four_names(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getHostname') m = mocker.patch('_slsdet.DetectorApi.getHostname')
m.return_value = 'beb059+beb048+beb120+beb153+' m.return_value = 'beb059+beb048+beb120+beb153+'
assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153'] assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153']
def test_decode_hostname_blank(d, mocker): def test_decode_hostname_blank(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getHostname') m = mocker.patch('_slsdet.DetectorApi.getHostname')
m.return_value = '' m.return_value = ''
assert d.hostname == [] assert d.hostname == []
def test_get_image_size_gives_correct_size(d, mocker): def test_get_image_size_gives_correct_size(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getImageSize') m = mocker.patch('_slsdet.DetectorApi.getImageSize')
m.return_value = (512,1024) m.return_value = (512,1024)
im_size = d.image_size im_size = d.image_size
assert im_size.rows == 512 assert im_size.rows == 512
@ -202,7 +202,7 @@ def test_get_image_size_gives_correct_size(d, mocker):
def test_load_config(d, mocker): def test_load_config(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') m = mocker.patch('_slsdet.DetectorApi.readConfigurationFile')
#To avoid raising an exception because path is not there #To avoid raising an exception because path is not there
mock_os = mocker.patch('os.path.isfile') mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = True mock_os.return_value = True
@ -210,14 +210,14 @@ def test_load_config(d, mocker):
m.assert_called_once_with('/path/to/my/file.config') m.assert_called_once_with('/path/to/my/file.config')
def test_load_config_raises_when_file_is_not_found(d, mocker): def test_load_config_raises_when_file_is_not_found(d, mocker):
mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') mocker.patch('_slsdet.DetectorApi.readConfigurationFile')
mock_os = mocker.patch('os.path.isfile') mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = False mock_os.return_value = False
with pytest.raises(FileNotFoundError): with pytest.raises(FileNotFoundError):
d.load_config('/path/to/my/file.config') d.load_config('/path/to/my/file.config')
def test_load_parameters(d, mocker): def test_load_parameters(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.readParametersFile') m = mocker.patch('_slsdet.DetectorApi.readParametersFile')
#To avoid raising an exception because path is not there #To avoid raising an exception because path is not there
mock_os = mocker.patch('os.path.isfile') mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = True mock_os.return_value = True
@ -225,7 +225,7 @@ def test_load_parameters(d, mocker):
m.assert_called_once_with('/path/to/my/file.par') m.assert_called_once_with('/path/to/my/file.par')
def test_load_parameters_raises_when_file_is_not_found(d, mocker): def test_load_parameters_raises_when_file_is_not_found(d, mocker):
mocker.patch('_sls_detector.DetectorApi.readParametersFile') mocker.patch('_slsdet.DetectorApi.readParametersFile')
mock_os = mocker.patch('os.path.isfile') mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = False mock_os.return_value = False
with pytest.raises(FileNotFoundError): with pytest.raises(FileNotFoundError):
@ -233,14 +233,14 @@ def test_load_parameters_raises_when_file_is_not_found(d, mocker):
#getDetectorGeometry #getDetectorGeometry
def test_get_module_geometry_gives_correct_size(d, mocker): def test_get_module_geometry_gives_correct_size(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') m = mocker.patch('_slsdet.DetectorApi.getDetectorGeometry')
m.return_value = (13,7) m.return_value = (13,7)
g = d.module_geometry g = d.module_geometry
assert g.vertical == 7 assert g.vertical == 7
assert g.horizontal == 13 assert g.horizontal == 13
def test_get_module_geometry_access(d, mocker): def test_get_module_geometry_access(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') m = mocker.patch('_slsdet.DetectorApi.getDetectorGeometry')
m.return_value = (12,3) m.return_value = (12,3)
assert d.module_geometry[0] == 12 assert d.module_geometry[0] == 12
assert d.module_geometry[1] == 3 assert d.module_geometry[1] == 3
@ -248,237 +248,237 @@ def test_get_module_geometry_access(d, mocker):
assert d.module_geometry.horizontal == 12 assert d.module_geometry.horizontal == 12
def test_get_n_frames(d, mocker): def test_get_n_frames(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNumberOfFrames') m = mocker.patch('_slsdet.DetectorApi.getNumberOfFrames')
m.return_value = 3 m.return_value = 3
assert d.n_frames == 3 assert d.n_frames == 3
def test_set_n_frames(d, mocker): def test_set_n_frames(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') m = mocker.patch('_slsdet.DetectorApi.setNumberOfFrames')
d.n_frames = 9 d.n_frames = 9
m.assert_called_once_with(9) m.assert_called_once_with(9)
def test_set_n_frames_raises_on_neg(d, mocker): def test_set_n_frames_raises_on_neg(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') mocker.patch('_slsdet.DetectorApi.setNumberOfFrames')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.n_frames = -1 d.n_frames = -1
def test_set_n_frames_raises_on_zero(d, mocker): def test_set_n_frames_raises_on_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') mocker.patch('_slsdet.DetectorApi.setNumberOfFrames')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.n_frames = 0 d.n_frames = 0
def test_get_n_modules(d, mocker): def test_get_n_modules(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') m = mocker.patch('_slsdet.DetectorApi.getNumberOfDetectors')
m.return_value = 12 m.return_value = 12
assert d.n_modules == 12 assert d.n_modules == 12
def test_get_period_time(d, mocker): def test_get_period_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getPeriod') m = mocker.patch('_slsdet.DetectorApi.getPeriod')
m.return_value = 130000000 m.return_value = 130000000
assert d.period == 0.13 assert d.period == 0.13
def test_set_period_time(d, mocker): def test_set_period_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setPeriod') m = mocker.patch('_slsdet.DetectorApi.setPeriod')
d.period = 1.953 d.period = 1.953
m.assert_called_once_with(1953000000) m.assert_called_once_with(1953000000)
def test_set_period_time_less_than_zero(d, mocker): def test_set_period_time_less_than_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setPeriod') mocker.patch('_slsdet.DetectorApi.setPeriod')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.period = -7 d.period = -7
def test_pulse_chip_call(d, mocker): def test_pulse_chip_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.pulseChip') m = mocker.patch('_slsdet.DetectorApi.pulseChip')
d.pulse_chip(15) d.pulse_chip(15)
m.assert_called_once_with(15) m.assert_called_once_with(15)
def test_pulse_chip_call_minus_one(d, mocker): def test_pulse_chip_call_minus_one(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.pulseChip') m = mocker.patch('_slsdet.DetectorApi.pulseChip')
d.pulse_chip(-1) d.pulse_chip(-1)
m.assert_called_once_with(-1) m.assert_called_once_with(-1)
def test_pulse_chip_asserts_on_smaller_than_minus_one(d, mocker): def test_pulse_chip_asserts_on_smaller_than_minus_one(d, mocker):
mocker.patch('_sls_detector.DetectorApi.pulseChip') mocker.patch('_slsdet.DetectorApi.pulseChip')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.pulse_chip(-3) d.pulse_chip(-3)
#--------------------------------------------------------------------subexptime #--------------------------------------------------------------------subexptime
def test_get_sub_exposure_time(d, mocker): def test_get_sub_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getSubExposureTime') m = mocker.patch('_slsdet.DetectorApi.getSubExposureTime')
m.return_value = 2370000 m.return_value = 2370000
assert d.sub_exposure_time == 0.00237 assert d.sub_exposure_time == 0.00237
def test_set_sub_exposure_time(d, mocker): def test_set_sub_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') m = mocker.patch('_slsdet.DetectorApi.setSubExposureTime')
d.sub_exposure_time = 0.002 d.sub_exposure_time = 0.002
m.assert_called_once_with(2000000) m.assert_called_once_with(2000000)
def test_set_sub_exposure_time_raises_on_zero(d, mocker): def test_set_sub_exposure_time_raises_on_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') mocker.patch('_slsdet.DetectorApi.setSubExposureTime')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.sub_exposure_time = 0 d.sub_exposure_time = 0
#-------------------------------------------------------------Rate correction #-------------------------------------------------------------Rate correction
def test_get_rate_correction(d, mocker): def test_get_rate_correction(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getRateCorrection') m = mocker.patch('_slsdet.DetectorApi.getRateCorrection')
m.return_value = [132,129] m.return_value = [132,129]
assert d.rate_correction == [132,129] assert d.rate_correction == [132,129]
def test_set_rate_correction(d, mocker): def test_set_rate_correction(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setRateCorrection') m = mocker.patch('_slsdet.DetectorApi.setRateCorrection')
mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') mock_n = mocker.patch('_slsdet.DetectorApi.getNumberOfDetectors')
mock_n.return_value = 3 mock_n.return_value = 3
d.rate_correction = [123,90,50] d.rate_correction = [123,90,50]
m.assert_called_once_with([123,90,50]) m.assert_called_once_with([123,90,50])
def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker): def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setRateCorrection') mocker.patch('_slsdet.DetectorApi.setRateCorrection')
mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') mock_n = mocker.patch('_slsdet.DetectorApi.getNumberOfDetectors')
mock_n.return_value = 4 mock_n.return_value = 4
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.rate_correction = [123,90,50] d.rate_correction = [123,90,50]
#----------------------------------------------------------------Readout clock #----------------------------------------------------------------Readout clock
def test_get_readout_clock_0(d, mocker): def test_get_readout_clock_0(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
m.return_value = 0 m.return_value = 0
assert d.readout_clock == 'Full Speed' assert d.readout_clock == 'Full Speed'
def test_get_readout_clock_1(d, mocker): def test_get_readout_clock_1(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
m.return_value = 1 m.return_value = 1
assert d.readout_clock == 'Half Speed' assert d.readout_clock == 'Half Speed'
def test_get_readout_clock_2(d, mocker): def test_get_readout_clock_2(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
m.return_value = 2 m.return_value = 2
assert d.readout_clock == 'Quarter Speed' assert d.readout_clock == 'Quarter Speed'
def test_get_readout_clock_3(d, mocker): def test_get_readout_clock_3(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
m.return_value = 3 m.return_value = 3
assert d.readout_clock == 'Super Slow Speed' assert d.readout_clock == 'Super Slow Speed'
def test_set_readout_clock_0(d, mocker): def test_set_readout_clock_0(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Full Speed' d.readout_clock = 'Full Speed'
m.assert_called_once_with(0) m.assert_called_once_with(0)
def test_set_readout_clock_1(d, mocker): def test_set_readout_clock_1(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Half Speed' d.readout_clock = 'Half Speed'
m.assert_called_once_with(1) m.assert_called_once_with(1)
def test_set_readout_clock_2(d, mocker): def test_set_readout_clock_2(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Quarter Speed' d.readout_clock = 'Quarter Speed'
m.assert_called_once_with(2) m.assert_called_once_with(2)
def test_set_readout_clock_3(d, mocker): def test_set_readout_clock_3(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Super Slow Speed' d.readout_clock = 'Super Slow Speed'
m.assert_called_once_with(3) m.assert_called_once_with(3)
#----------------------------------------------------------------rx_datastream #----------------------------------------------------------------rx_datastream
def test_get_rx_datastream(d, mocker): def test_get_rx_datastream(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getRxDataStreamStatus') m = mocker.patch('_slsdet.DetectorApi.getRxDataStreamStatus')
m.return_value = False m.return_value = False
assert d.rx_datastream == False assert d.rx_datastream == False
def test_set_rx_datastream(d, mocker): def test_set_rx_datastream(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setRxDataStreamStatus') m = mocker.patch('_slsdet.DetectorApi.setRxDataStreamStatus')
d.rx_datastream = True d.rx_datastream = True
m.assert_called_once_with(True) m.assert_called_once_with(True)
def test_get_rx_zmqip(d, mocker): def test_get_rx_zmqip(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
d.rx_zmqip d.rx_zmqip
m.assert_called_once_with('rx_zmqip') m.assert_called_once_with('rx_zmqip')
def test_get_rx_zmqport_call(d, mocker): def test_get_rx_zmqport_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
d.rx_zmqport d.rx_zmqport
m.assert_called_once_with('rx_zmqport') m.assert_called_once_with('rx_zmqport')
def test_get_rx_zmqport_decode(d, mocker): def test_get_rx_zmqport_decode(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
m.return_value = '30001+30003+' m.return_value = '30001+30003+'
assert d.rx_zmqport == [30001, 30002, 30003, 30004] assert d.rx_zmqport == [30001, 30002, 30003, 30004]
def test_get_rx_zmqport_empty(d, mocker): def test_get_rx_zmqport_empty(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
m.return_value = '' m.return_value = ''
assert d.rx_zmqport == [] assert d.rx_zmqport == []
#--------------------------------------------------------------------status #--------------------------------------------------------------------status
def test_status_call(d, mocker): def test_status_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getRunStatus') m = mocker.patch('_slsdet.DetectorApi.getRunStatus')
d.status d.status
m.assert_called_once_with() m.assert_called_once_with()
def test_start_acq_call(d, mocker): def test_start_acq_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.startAcquisition') m = mocker.patch('_slsdet.DetectorApi.startAcquisition')
d.start_acq() d.start_acq()
m.assert_called_once_with() m.assert_called_once_with()
def test_stop_acq_call(d, mocker): def test_stop_acq_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.stopAcquisition') m = mocker.patch('_slsdet.DetectorApi.stopAcquisition')
d.stop_acq() d.stop_acq()
m.assert_called_once_with() m.assert_called_once_with()
#--------------------------------------------------------------------subexptime #--------------------------------------------------------------------subexptime
def test_get_sub_exposure_time(d, mocker): def test_get_sub_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getSubExposureTime') m = mocker.patch('_slsdet.DetectorApi.getSubExposureTime')
m.return_value = 2370000 m.return_value = 2370000
assert d.sub_exposure_time == 0.00237 assert d.sub_exposure_time == 0.00237
def test_set_sub_exposure_time(d, mocker): def test_set_sub_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') m = mocker.patch('_slsdet.DetectorApi.setSubExposureTime')
d.sub_exposure_time = 0.002 d.sub_exposure_time = 0.002
m.assert_called_once_with(2000000) m.assert_called_once_with(2000000)
def test_set_sub_exposure_time_raises_on_zero(d, mocker): def test_set_sub_exposure_time_raises_on_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') mocker.patch('_slsdet.DetectorApi.setSubExposureTime')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.sub_exposure_time = 0 d.sub_exposure_time = 0
#------------------------------------------------------------------timing mode #------------------------------------------------------------------timing mode
def test_get_timing_mode(d, mocker): def test_get_timing_mode(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getTimingMode') m = mocker.patch('_slsdet.DetectorApi.getTimingMode')
d.timing_mode d.timing_mode
m.assert_called_once_with() m.assert_called_once_with()
def test_set_timing_mode(d, mocker): def test_set_timing_mode(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setTimingMode') m = mocker.patch('_slsdet.DetectorApi.setTimingMode')
d.timing_mode = 'auto' d.timing_mode = 'auto'
m.assert_called_once_with('auto') m.assert_called_once_with('auto')
#----------------------------------------------------------------vthreshold #----------------------------------------------------------------vthreshold
def test_get_vthreshold(d, mocker): def test_get_vthreshold(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDac') m = mocker.patch('_slsdet.DetectorApi.getDac')
d.vthreshold d.vthreshold
m.assert_called_once_with('vthreshold', -1) m.assert_called_once_with('vthreshold', -1)
def test_set_vthreshold(d, mocker): def test_set_vthreshold(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDac') m = mocker.patch('_slsdet.DetectorApi.setDac')
d.vthreshold = 1675 d.vthreshold = 1675
m.assert_called_once_with('vthreshold', -1, 1675) m.assert_called_once_with('vthreshold', -1, 1675)
#----------------------------------------------------------------trimbits #----------------------------------------------------------------trimbits
def test_get_trimbits(d, mocker): def test_get_trimbits(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getAllTrimbits') m = mocker.patch('_slsdet.DetectorApi.getAllTrimbits')
d.trimbits d.trimbits
m.assert_called_once_with() m.assert_called_once_with()
def test_set_trimbits(d, mocker): def test_set_trimbits(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setAllTrimbits') m = mocker.patch('_slsdet.DetectorApi.setAllTrimbits')
d.trimbits = 15 d.trimbits = 15
m.assert_called_once_with(15) m.assert_called_once_with(15)
def test_set_trimbits_raises_outside_range(d, mocker): def test_set_trimbits_raises_outside_range(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setAllTrimbits') mocker.patch('_slsdet.DetectorApi.setAllTrimbits')
with pytest.raises(ValueError): with pytest.raises(ValueError):
d.trimbits = 69 d.trimbits = 69

View File

@ -15,7 +15,7 @@ from pytest_mock import mocker
import sys import sys
sys.path.append('/home/l_frojdh/slsdetectorgrup/sls_detector') sys.path.append('/home/l_frojdh/slsdetectorgrup/sls_detector')
import _sls_detector import _slsdet
from sls_detector.errors import DetectorValueError, DetectorError from sls_detector.errors import DetectorValueError, DetectorError
from sls_detector.utils import all_equal, element_if_equal from sls_detector.utils import all_equal, element_if_equal
@ -47,7 +47,7 @@ def test_set_counters_single(d, mocker):
# def test_busy_call(d, mocker): # def test_busy_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getAcquiringFlag') # m = mocker.patch('_slsdet.DetectorApi.getAcquiringFlag')
# m.return_value = False # m.return_value = False
# assert d.busy == False # assert d.busy == False
@ -73,34 +73,34 @@ def test_set_counters_single(d, mocker):
# d.detector_type = 'Eiger' # d.detector_type = 'Eiger'
# def test_det_type(d, mocker): # def test_det_type(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDetectorType') # m = mocker.patch('_slsdet.DetectorApi.getDetectorType')
# m.return_value = 'Eiger' # m.return_value = 'Eiger'
# assert d.detector_type == 'Eiger' # assert d.detector_type == 'Eiger'
# def test_get_exposure_time(d, mocker): # def test_get_exposure_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getExposureTime') # m = mocker.patch('_slsdet.DetectorApi.getExposureTime')
# m.return_value = 100000000 # m.return_value = 100000000
# assert d.exposure_time == 0.1 # assert d.exposure_time == 0.1
# def test_set_exposure_time(d, mocker): # def test_set_exposure_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setExposureTime') # m = mocker.patch('_slsdet.DetectorApi.setExposureTime')
# d.exposure_time = 1.5 # d.exposure_time = 1.5
# m.assert_called_once_with(1500000000) # m.assert_called_once_with(1500000000)
# def test_set_exposure_time_less_than_zero(d, mocker): # def test_set_exposure_time_less_than_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setExposureTime') # mocker.patch('_slsdet.DetectorApi.setExposureTime')
# with pytest.raises(DetectorValueError): # with pytest.raises(DetectorValueError):
# d.exposure_time = -7 # d.exposure_time = -7
# def test_get_file_index(d, mocker): # def test_get_file_index(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFileIndex') # m = mocker.patch('_slsdet.DetectorApi.getFileIndex')
# m.return_value = 8 # m.return_value = 8
# assert d.file_index == 8 # assert d.file_index == 8
# def test_set_file_index(d, mocker): # def test_set_file_index(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFileIndex') # m = mocker.patch('_slsdet.DetectorApi.setFileIndex')
# d.file_index = 9 # d.file_index = 9
# m.assert_called_with(9) # m.assert_called_with(9)
@ -112,28 +112,28 @@ def test_set_counters_single(d, mocker):
# assert d.dynamic_range == -100 # assert d.dynamic_range == -100
# def test_set_file_index_raises_on_neg(d, mocker): # def test_set_file_index_raises_on_neg(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setFileIndex') # mocker.patch('_slsdet.DetectorApi.setFileIndex')
# with pytest.raises(ValueError): # with pytest.raises(ValueError):
# d.file_index = -9 # d.file_index = -9
# def test_get_file_name(d, mocker): # def test_get_file_name(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFileName') # m = mocker.patch('_slsdet.DetectorApi.getFileName')
# d.file_name # d.file_name
# m.assert_called_once_with() # m.assert_called_once_with()
# def test_set_file_name(d, mocker): # def test_set_file_name(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFileName') # m = mocker.patch('_slsdet.DetectorApi.setFileName')
# d.file_name = 'hej' # d.file_name = 'hej'
# m.assert_called_once_with('hej') # m.assert_called_once_with('hej')
# def test_get_file_path(d, mocker): # def test_get_file_path(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFilePath') # m = mocker.patch('_slsdet.DetectorApi.getFilePath')
# d.file_path # d.file_path
# m.assert_called_once_with() # m.assert_called_once_with()
# def test_set_file_path_when_path_exists(d, mocker): # def test_set_file_path_when_path_exists(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFilePath') # m = mocker.patch('_slsdet.DetectorApi.setFilePath')
# #To avoid raising an exception because path is not there # #To avoid raising an exception because path is not there
# mock_os = mocker.patch('os.path.exists') # mock_os = mocker.patch('os.path.exists')
# mock_os.return_value = True # mock_os.return_value = True
@ -141,25 +141,25 @@ def test_set_counters_single(d, mocker):
# m.assert_called_once_with('/path/to/something/') # m.assert_called_once_with('/path/to/something/')
# def test_set_file_path_raises_when_not_exists(d, mocker): # def test_set_file_path_raises_when_not_exists(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setFilePath') # mocker.patch('_slsdet.DetectorApi.setFilePath')
# mock_os = mocker.patch('os.path.exists') # mock_os = mocker.patch('os.path.exists')
# mock_os.return_value = False # mock_os.return_value = False
# with pytest.raises(FileNotFoundError): # with pytest.raises(FileNotFoundError):
# d.file_path = '/path/to/something/' # d.file_path = '/path/to/something/'
# def test_get_file_write(d, mocker): # def test_get_file_write(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFileWrite') # m = mocker.patch('_slsdet.DetectorApi.getFileWrite')
# m.return_value = False # m.return_value = False
# assert d.file_write == False # assert d.file_write == False
# def test_set_file_write(d, mocker): # def test_set_file_write(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFileWrite') # m = mocker.patch('_slsdet.DetectorApi.setFileWrite')
# d.file_write = True # d.file_write = True
# m.assert_called_once_with(True) # m.assert_called_once_with(True)
# def test_get_firmware_version(d, mocker): # def test_get_firmware_version(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFirmwareVersion') # m = mocker.patch('_slsdet.DetectorApi.getFirmwareVersion')
# m.return_value = 20 # m.return_value = 20
# assert d.firmware_version == 20 # assert d.firmware_version == 20
@ -168,38 +168,38 @@ def test_set_counters_single(d, mocker):
# d.firmware_version = 20 # d.firmware_version = 20
# def test_get_high_voltage_call_signature(d, mocker): # def test_get_high_voltage_call_signature(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDac') # m = mocker.patch('_slsdet.DetectorApi.getDac')
# d.high_voltage # d.high_voltage
# m.assert_called_once_with('vhighvoltage', -1) # m.assert_called_once_with('vhighvoltage', -1)
# def test_get_high_voltage(d, mocker): # def test_get_high_voltage(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDac') # m = mocker.patch('_slsdet.DetectorApi.getDac')
# m.return_value = 80 # m.return_value = 80
# assert d.high_voltage == 80 # assert d.high_voltage == 80
# #self._api.setDac('vhighvoltage', -1, voltage) # #self._api.setDac('vhighvoltage', -1, voltage)
# def test_set_high_voltage(d, mocker): # def test_set_high_voltage(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setDac') # m = mocker.patch('_slsdet.DetectorApi.setDac')
# d.high_voltage = 80 # d.high_voltage = 80
# m.assert_called_once_with('vhighvoltage', -1, 80) # m.assert_called_once_with('vhighvoltage', -1, 80)
# def test_decode_hostname_two_names(d, mocker): # def test_decode_hostname_two_names(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getHostname') # m = mocker.patch('_slsdet.DetectorApi.getHostname')
# m.return_value = 'beb059+beb048+' # m.return_value = 'beb059+beb048+'
# assert d.hostname == ['beb059', 'beb048'] # assert d.hostname == ['beb059', 'beb048']
# def test_decode_hostname_four_names(d, mocker): # def test_decode_hostname_four_names(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getHostname') # m = mocker.patch('_slsdet.DetectorApi.getHostname')
# m.return_value = 'beb059+beb048+beb120+beb153+' # m.return_value = 'beb059+beb048+beb120+beb153+'
# assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153'] # assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153']
# def test_decode_hostname_blank(d, mocker): # def test_decode_hostname_blank(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getHostname') # m = mocker.patch('_slsdet.DetectorApi.getHostname')
# m.return_value = '' # m.return_value = ''
# assert d.hostname == [] # assert d.hostname == []
# def test_get_image_size_gives_correct_size(d, mocker): # def test_get_image_size_gives_correct_size(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getImageSize') # m = mocker.patch('_slsdet.DetectorApi.getImageSize')
# m.return_value = (512,1024) # m.return_value = (512,1024)
# im_size = d.image_size # im_size = d.image_size
# assert im_size.rows == 512 # assert im_size.rows == 512
@ -208,7 +208,7 @@ def test_set_counters_single(d, mocker):
# def test_load_config(d, mocker): # def test_load_config(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') # m = mocker.patch('_slsdet.DetectorApi.readConfigurationFile')
# #To avoid raising an exception because path is not there # #To avoid raising an exception because path is not there
# mock_os = mocker.patch('os.path.isfile') # mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = True # mock_os.return_value = True
@ -216,14 +216,14 @@ def test_set_counters_single(d, mocker):
# m.assert_called_once_with('/path/to/my/file.config') # m.assert_called_once_with('/path/to/my/file.config')
# def test_load_config_raises_when_file_is_not_found(d, mocker): # def test_load_config_raises_when_file_is_not_found(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') # mocker.patch('_slsdet.DetectorApi.readConfigurationFile')
# mock_os = mocker.patch('os.path.isfile') # mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = False # mock_os.return_value = False
# with pytest.raises(FileNotFoundError): # with pytest.raises(FileNotFoundError):
# d.load_config('/path/to/my/file.config') # d.load_config('/path/to/my/file.config')
# def test_load_parameters(d, mocker): # def test_load_parameters(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.readParametersFile') # m = mocker.patch('_slsdet.DetectorApi.readParametersFile')
# #To avoid raising an exception because path is not there # #To avoid raising an exception because path is not there
# mock_os = mocker.patch('os.path.isfile') # mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = True # mock_os.return_value = True
@ -231,7 +231,7 @@ def test_set_counters_single(d, mocker):
# m.assert_called_once_with('/path/to/my/file.par') # m.assert_called_once_with('/path/to/my/file.par')
# def test_load_parameters_raises_when_file_is_not_found(d, mocker): # def test_load_parameters_raises_when_file_is_not_found(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.readParametersFile') # mocker.patch('_slsdet.DetectorApi.readParametersFile')
# mock_os = mocker.patch('os.path.isfile') # mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = False # mock_os.return_value = False
# with pytest.raises(FileNotFoundError): # with pytest.raises(FileNotFoundError):
@ -239,14 +239,14 @@ def test_set_counters_single(d, mocker):
# #getDetectorGeometry # #getDetectorGeometry
# def test_get_module_geometry_gives_correct_size(d, mocker): # def test_get_module_geometry_gives_correct_size(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') # m = mocker.patch('_slsdet.DetectorApi.getDetectorGeometry')
# m.return_value = (13,7) # m.return_value = (13,7)
# g = d.module_geometry # g = d.module_geometry
# assert g.vertical == 7 # assert g.vertical == 7
# assert g.horizontal == 13 # assert g.horizontal == 13
# def test_get_module_geometry_access(d, mocker): # def test_get_module_geometry_access(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') # m = mocker.patch('_slsdet.DetectorApi.getDetectorGeometry')
# m.return_value = (12,3) # m.return_value = (12,3)
# assert d.module_geometry[0] == 12 # assert d.module_geometry[0] == 12
# assert d.module_geometry[1] == 3 # assert d.module_geometry[1] == 3
@ -259,12 +259,12 @@ def test_set_counters_single(d, mocker):
# assert t.vertical == 0 # assert t.vertical == 0
# def test_get_n_frames(d, mocker): # def test_get_n_frames(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNumberOfFrames') # m = mocker.patch('_slsdet.DetectorApi.getNumberOfFrames')
# m.return_value = 3 # m.return_value = 3
# assert d.n_frames == 3 # assert d.n_frames == 3
# def test_set_n_frames(d, mocker): # def test_set_n_frames(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') # m = mocker.patch('_slsdet.DetectorApi.setNumberOfFrames')
# d.n_frames = 9 # d.n_frames = 9
# m.assert_called_once_with(9) # m.assert_called_once_with(9)
@ -272,12 +272,12 @@ def test_set_counters_single(d, mocker):
# assert d.n_frames == -100 # assert d.n_frames == -100
# def test_set_n_frames_raises_on_neg(d, mocker): # def test_set_n_frames_raises_on_neg(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') # mocker.patch('_slsdet.DetectorApi.setNumberOfFrames')
# with pytest.raises(DetectorValueError): # with pytest.raises(DetectorValueError):
# d.n_frames = -1 # d.n_frames = -1
# def test_set_n_frames_raises_on_zero(d, mocker): # def test_set_n_frames_raises_on_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') # mocker.patch('_slsdet.DetectorApi.setNumberOfFrames')
# with pytest.raises(DetectorValueError): # with pytest.raises(DetectorValueError):
# d.n_frames = 0 # d.n_frames = 0
@ -285,12 +285,12 @@ def test_set_counters_single(d, mocker):
# assert d.n_cycles == -100 # assert d.n_cycles == -100
# def test_set_n_cycles_raises_on_zero(d, mocker): # def test_set_n_cycles_raises_on_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setCycles') # mocker.patch('_slsdet.DetectorApi.setCycles')
# with pytest.raises(DetectorValueError): # with pytest.raises(DetectorValueError):
# d.n_cycles = 0 # d.n_cycles = 0
# def test_set_n_cycles(d, mocker): # def test_set_n_cycles(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setCycles') # m = mocker.patch('_slsdet.DetectorApi.setCycles')
# d.n_cycles = 56 # d.n_cycles = 56
# m.assert_called_once_with(56) # m.assert_called_once_with(56)
@ -300,12 +300,12 @@ def test_set_counters_single(d, mocker):
# assert d.n_measurements == -100 # assert d.n_measurements == -100
# def test_set_n_measurements_raises_on_zero(d, mocker): # def test_set_n_measurements_raises_on_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements') # mocker.patch('_slsdet.DetectorApi.setNumberOfMeasurements')
# with pytest.raises(DetectorValueError): # with pytest.raises(DetectorValueError):
# d.n_measurements = 0 # d.n_measurements = 0
# def test_set_n_measurements(d, mocker): # def test_set_n_measurements(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements') # m = mocker.patch('_slsdet.DetectorApi.setNumberOfMeasurements')
# d.n_measurements = 560 # d.n_measurements = 560
# m.assert_called_once_with(560) # m.assert_called_once_with(560)
@ -313,33 +313,33 @@ def test_set_counters_single(d, mocker):
# assert d.n_modules == 0 # assert d.n_modules == 0
# def test_get_n_modules(d, mocker): # def test_get_n_modules(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') # m = mocker.patch('_slsdet.DetectorApi.getNumberOfDetectors')
# m.return_value = 12 # m.return_value = 12
# assert d.n_modules == 12 # assert d.n_modules == 12
# def test_get_period_time(d, mocker): # def test_get_period_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getPeriod') # m = mocker.patch('_slsdet.DetectorApi.getPeriod')
# m.return_value = 130000000 # m.return_value = 130000000
# assert d.period == 0.13 # assert d.period == 0.13
# def test_set_period_time(d, mocker): # def test_set_period_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setPeriod') # m = mocker.patch('_slsdet.DetectorApi.setPeriod')
# d.period = 1.953 # d.period = 1.953
# m.assert_called_once_with(1953000000) # m.assert_called_once_with(1953000000)
# def test_set_period_time_less_than_zero(d, mocker): # def test_set_period_time_less_than_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setPeriod') # mocker.patch('_slsdet.DetectorApi.setPeriod')
# with pytest.raises(ValueError): # with pytest.raises(ValueError):
# d.period = -7 # d.period = -7
# def test_get_online(d, mocker): # def test_get_online(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getOnline') # m = mocker.patch('_slsdet.DetectorApi.getOnline')
# d.online # d.online
# m.assert_called_once_with() # m.assert_called_once_with()
# def test_set_online(d, mocker): # def test_set_online(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setOnline') # m = mocker.patch('_slsdet.DetectorApi.setOnline')
# d.online = True # d.online = True
# m.assert_called_once_with(True) # m.assert_called_once_with(True)
@ -347,116 +347,116 @@ def test_set_counters_single(d, mocker):
# assert d.last_client_ip == '' # assert d.last_client_ip == ''
# def test_last_cliten_ip_call(d, mocker): # def test_last_cliten_ip_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getLastClientIP') # m = mocker.patch('_slsdet.DetectorApi.getLastClientIP')
# d.last_client_ip # d.last_client_ip
# m.assert_called_once_with() # m.assert_called_once_with()
# #-------------------------------------------------------------Rate correction # #-------------------------------------------------------------Rate correction
# def test_get_rate_correction(d, mocker): # def test_get_rate_correction(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getRateCorrection') # m = mocker.patch('_slsdet.DetectorApi.getRateCorrection')
# m.return_value = [132,129] # m.return_value = [132,129]
# assert d.rate_correction == [132,129] # assert d.rate_correction == [132,129]
# def test_set_rate_correction(d, mocker): # def test_set_rate_correction(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setRateCorrection') # m = mocker.patch('_slsdet.DetectorApi.setRateCorrection')
# mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') # mock_n = mocker.patch('_slsdet.DetectorApi.getNumberOfDetectors')
# mock_n.return_value = 3 # mock_n.return_value = 3
# d.rate_correction = [123,90,50] # d.rate_correction = [123,90,50]
# m.assert_called_once_with([123,90,50]) # m.assert_called_once_with([123,90,50])
# def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker): # def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setRateCorrection') # mocker.patch('_slsdet.DetectorApi.setRateCorrection')
# mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') # mock_n = mocker.patch('_slsdet.DetectorApi.getNumberOfDetectors')
# mock_n.return_value = 4 # mock_n.return_value = 4
# with pytest.raises(ValueError): # with pytest.raises(ValueError):
# d.rate_correction = [123,90,50] # d.rate_correction = [123,90,50]
# #----------------------------------------------------------------Readout clock # #----------------------------------------------------------------Readout clock
# def test_get_readout_clock_0(d, mocker): # def test_get_readout_clock_0(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
# m.return_value = 0 # m.return_value = 0
# assert d.readout_clock == 'Full Speed' # assert d.readout_clock == 'Full Speed'
# def test_get_readout_clock_1(d, mocker): # def test_get_readout_clock_1(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
# m.return_value = 1 # m.return_value = 1
# assert d.readout_clock == 'Half Speed' # assert d.readout_clock == 'Half Speed'
# def test_get_readout_clock_2(d, mocker): # def test_get_readout_clock_2(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
# m.return_value = 2 # m.return_value = 2
# assert d.readout_clock == 'Quarter Speed' # assert d.readout_clock == 'Quarter Speed'
# def test_get_readout_clock_3(d, mocker): # def test_get_readout_clock_3(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.getReadoutClockSpeed')
# m.return_value = 3 # m.return_value = 3
# assert d.readout_clock == 'Super Slow Speed' # assert d.readout_clock == 'Super Slow Speed'
# def test_set_readout_clock_0(d, mocker): # def test_set_readout_clock_0(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Full Speed' # d.readout_clock = 'Full Speed'
# m.assert_called_once_with(0) # m.assert_called_once_with(0)
# def test_set_readout_clock_1(d, mocker): # def test_set_readout_clock_1(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Half Speed' # d.readout_clock = 'Half Speed'
# m.assert_called_once_with(1) # m.assert_called_once_with(1)
# def test_set_readout_clock_2(d, mocker): # def test_set_readout_clock_2(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Quarter Speed' # d.readout_clock = 'Quarter Speed'
# m.assert_called_once_with(2) # m.assert_called_once_with(2)
# def test_set_readout_clock_3(d, mocker): # def test_set_readout_clock_3(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') # m = mocker.patch('_slsdet.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Super Slow Speed' # d.readout_clock = 'Super Slow Speed'
# m.assert_called_once_with(3) # m.assert_called_once_with(3)
# #----------------------------------------------------------------rx_datastream # #----------------------------------------------------------------rx_datastream
# def test_get_rx_datastream(d, mocker): # def test_get_rx_datastream(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getRxDataStreamStatus') # m = mocker.patch('_slsdet.DetectorApi.getRxDataStreamStatus')
# m.return_value = False # m.return_value = False
# assert d.rx_datastream == False # assert d.rx_datastream == False
# def test_set_rx_datastream(d, mocker): # def test_set_rx_datastream(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setRxDataStreamStatus') # m = mocker.patch('_slsdet.DetectorApi.setRxDataStreamStatus')
# d.rx_datastream = True # d.rx_datastream = True
# m.assert_called_once_with(True) # m.assert_called_once_with(True)
# def test_get_rx_zmqip(d, mocker): # def test_get_rx_zmqip(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') # m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
# d.rx_zmqip # d.rx_zmqip
# m.assert_called_once_with('rx_zmqip') # m.assert_called_once_with('rx_zmqip')
# def test_get_rx_zmqport_call(d, mocker): # def test_get_rx_zmqport_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') # m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
# d.rx_zmqport # d.rx_zmqport
# m.assert_called_once_with('rx_zmqport') # m.assert_called_once_with('rx_zmqport')
# def test_get_rx_zmqport_decode(d, mocker): # def test_get_rx_zmqport_decode(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') # m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
# m.return_value = ['30001', '30003'] # m.return_value = ['30001', '30003']
# assert d.rx_zmqport == [30001, 30003] # assert d.rx_zmqport == [30001, 30003]
# def test_get_rx_zmqport_empty(d, mocker): # def test_get_rx_zmqport_empty(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') # m = mocker.patch('_slsdet.DetectorApi.getNetworkParameter')
# m.return_value = '' # m.return_value = ''
# assert d.rx_zmqport == [] # assert d.rx_zmqport == []
# #--------------------------------------------------------------------status # #--------------------------------------------------------------------status
# def test_status_call(d, mocker): # def test_status_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getRunStatus') # m = mocker.patch('_slsdet.DetectorApi.getRunStatus')
# d.status # d.status
# m.assert_called_once_with() # m.assert_called_once_with()
# def test_start_detecor(d, mocker): # def test_start_detecor(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.startAcquisition') # m = mocker.patch('_slsdet.DetectorApi.startAcquisition')
# d.start_detector() # d.start_detector()
# m.assert_called_once_with() # m.assert_called_once_with()
# def test_stop_acq_call(d, mocker): # def test_stop_acq_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.stopAcquisition') # m = mocker.patch('_slsdet.DetectorApi.stopAcquisition')
# d.stop_detector() # d.stop_detector()
# m.assert_called_once_with() # m.assert_called_once_with()
@ -464,23 +464,23 @@ def test_set_counters_single(d, mocker):
# #------------------------------------------------------------------timing mode # #------------------------------------------------------------------timing mode
# def test_get_timing_mode(d, mocker): # def test_get_timing_mode(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getTimingMode') # m = mocker.patch('_slsdet.DetectorApi.getTimingMode')
# d.timing_mode # d.timing_mode
# m.assert_called_once_with() # m.assert_called_once_with()
# def test_set_timing_mode(d, mocker): # def test_set_timing_mode(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setTimingMode') # m = mocker.patch('_slsdet.DetectorApi.setTimingMode')
# d.timing_mode = 'auto' # d.timing_mode = 'auto'
# m.assert_called_once_with('auto') # m.assert_called_once_with('auto')
# #----------------------------------------------------------------vthreshold # #----------------------------------------------------------------vthreshold
# def test_get_vthreshold(d, mocker): # def test_get_vthreshold(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDac') # m = mocker.patch('_slsdet.DetectorApi.getDac')
# d.vthreshold # d.vthreshold
# m.assert_called_once_with('vthreshold', -1) # m.assert_called_once_with('vthreshold', -1)
# def test_set_vthreshold(d, mocker): # def test_set_vthreshold(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setDac') # m = mocker.patch('_slsdet.DetectorApi.setDac')
# d.vthreshold = 1675 # d.vthreshold = 1675
# m.assert_called_once_with('vthreshold', -1, 1675) # m.assert_called_once_with('vthreshold', -1, 1675)

View File

@ -19,3 +19,18 @@ target_link_libraries(result
set_target_properties(result PROPERTIES set_target_properties(result PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
) )
add_executable(udp udp.cpp)
target_link_libraries(udp
slsDetectorShared
slsSupportLib
pthread
rt
fmt
)
set_target_properties(udp PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)

65
sample/udp.cpp Normal file
View File

@ -0,0 +1,65 @@
#include "UdpRxSocket.h"
#include "sls_detector_defs.h"
#include <chrono>
#include <fmt/format.h>
#include <iostream>
#include <thread>
#include "network_utils.h"
// Assume packages arrive in order
// Assume frame nr starts from 0
using header_t = slsDetectorDefs::sls_detector_header;
int main() {
fmt::print("Hej!\n");
constexpr ssize_t packet_size = 4144;
constexpr ssize_t payload_size = packet_size - sizeof(header_t);
int port = 50012;
char * buffer = new char[packet_size];
sls::UdpRxSocket s(port, packet_size, "10.1.1.107");
int n = 0;
while(true){
// s.ReceiveDataOnly(buffer);
if (s.ReceivePacket())
std::cout << n++ << std::endl;
}
// auto header = reinterpret_cast<header_t *>(s.buffer());
// char *data = s.buffer() + sizeof(header_t);
// fmt::print("buffer start: {}\nheader: {}\ndata: {}\n", fmt::ptr(s.buffer()),
// fmt::ptr(header), fmt::ptr(data));
// int n = 0;
// fmt::print("Buffer size: {}\n", s.buffer_size());
// std::vector<uint16_t> image(n_pixels);
// char *image_data = (char *)image.data();
// uint64_t frame_nr = 0;
// while (true) {
// if (s.ReceivePacket()) {
// // fmt::print("frame: {} pkt: {} dst: {}\n", header->frameNumber,
// // header->packetNumber, header->packetNumber*payload_size);
// if (header->frameNumber != frame_nr) {
// // dispatch frame
// fmt::print("frame {} done! got: {} pkgs\n", frame_nr, n);
// frame_nr = header->frameNumber;
// n = 0;
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// }
// ++n;
// memcpy(image_data + header->packetNumber * payload_size, data,
// payload_size);
// } else {
// std::cout << "timeout\n";
// }
// }
}

View File

@ -17,7 +17,7 @@
#include <pthread.h> #include <pthread.h>
#include "analogDetector.h" #include "analogDetector.h"
#include "circularFifo.h" #include "CircularFifo.h"
#include <unistd.h> #include <unistd.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>

View File

@ -1,5 +1,8 @@
set(CMAKE_AUTOMOC ON) set(CMAKE_AUTOMOC ON)
find_package(PNG REQUIRED)
find_package(ZLIB REQUIRED)
set(SOURCES set(SOURCES
slsDetectorPlotting/src/SlsQt1DPlot.cxx slsDetectorPlotting/src/SlsQt1DPlot.cxx
slsDetectorPlotting/src/SlsQt1DZoomer.cxx slsDetectorPlotting/src/SlsQt1DZoomer.cxx
@ -89,8 +92,8 @@ target_link_libraries(slsDetectorGui PUBLIC
${QT_QTCORE_LIBRARIES} ${QT_QTCORE_LIBRARIES}
${QT_QTGUI_LIBRARIES} ${QT_QTGUI_LIBRARIES}
${QWT_LIBRARIES} ${QWT_LIBRARIES}
png PNG::PNG
z ZLIB::ZLIB
Qt4::QtOpenGL Qt4::QtOpenGL
Qt4::QtSvg Qt4::QtSvg
) )

View File

@ -160,4 +160,5 @@ class qDrawPlot : public QWidget, private Ui::PlotObject {
unsigned int nPixelsY{0}; unsigned int nPixelsY{0};
const static int npixelsx_jctb = 400; const static int npixelsx_jctb = 400;
int npixelsy_jctb{0}; int npixelsy_jctb{0};
uint32_t pixelMask{0};
}; };

View File

@ -229,6 +229,7 @@ void qDetectorMain::SetUpDetector(const std::string fName, int multiID) {
case slsDetectorDefs::JUNGFRAU: case slsDetectorDefs::JUNGFRAU:
case slsDetectorDefs::MOENCH: case slsDetectorDefs::MOENCH:
case slsDetectorDefs::MYTHEN3: case slsDetectorDefs::MYTHEN3:
case slsDetectorDefs::GOTTHARD2:
break; break;
default: default:
std::ostringstream os; std::ostringstream os;
@ -446,7 +447,7 @@ void qDetectorMain::ExecuteHelp(QAction *action) {
clientVersion + clientVersion +
"<br><br>" "<br><br>"
"Common GUI to control the SLS Detectors: " "Common GUI to control the SLS Detectors: "
"Eiger, Gotthard, Jungfrau and Moench.<br><br>" "Eiger, Jungfrau, Mythen3, Gotthard, Gotthard2 and Moench.<br><br>"
"It can be operated in parallel with the command " "It can be operated in parallel with the command "
"line interface:<br>" "line interface:<br>"
"sls_detector_put,<br>sls_detector_get,<br>sls_" "sls_detector_put,<br>sls_detector_get,<br>sls_"

View File

@ -52,6 +52,19 @@ qDrawPlot::~qDrawPlot() {
void qDrawPlot::SetupWidgetWindow() { void qDrawPlot::SetupWidgetWindow() {
detType = det->getDetectorType().squash(); detType = det->getDetectorType().squash();
switch (detType) {
case slsDetectorDefs::JUNGFRAU:
case slsDetectorDefs::MOENCH:
pixelMask = ((1 << 15) - 1);
FILE_LOG(logINFO) << "Pixel Mask: " << std::hex << pixelMask << std::dec;
break;
case slsDetectorDefs::GOTTHARD2:
pixelMask = ((1 << 13) - 1);
FILE_LOG(logINFO) << "Pixel Mask: " << std::hex << pixelMask << std::dec;
break;
default:
break;
}
// save // save
try { try {
std::string temp = det->getFilePath().squash("/tmp/"); std::string temp = det->getFilePath().squash("/tmp/");
@ -317,9 +330,11 @@ void qDrawPlot::SetDataCallBack(bool enable) {
FILE_LOG(logINFO) << "Setting data call back to " << std::boolalpha << enable << std::noboolalpha; FILE_LOG(logINFO) << "Setting data call back to " << std::boolalpha << enable << std::noboolalpha;
if (enable) { if (enable) {
isPlot = true; isPlot = true;
det->setRxZmqDataStream(true);
det->registerDataCallback(&(GetDataCallBack), this); det->registerDataCallback(&(GetDataCallBack), this);
} else { } else {
isPlot = false; isPlot = false;
det->setRxZmqDataStream(false);
det->registerDataCallback(nullptr, this); det->registerDataCallback(nullptr, this);
} }
@ -879,7 +894,7 @@ void qDrawPlot::toDoublePixelData(double *dest, char *source, int size, int data
int halfbyte = 0; int halfbyte = 0;
char cbyte = '\0'; char cbyte = '\0';
// mythen 3 debugging // mythen3 / gotthard2 debugging
int discardBits = numDiscardBits; int discardBits = numDiscardBits;
switch (dr) { switch (dr) {
@ -903,14 +918,15 @@ void qDrawPlot::toDoublePixelData(double *dest, char *source, int size, int data
case 16: case 16:
if (detType == slsDetectorDefs::JUNGFRAU || if (detType == slsDetectorDefs::JUNGFRAU ||
detType == slsDetectorDefs::MOENCH) { detType == slsDetectorDefs::MOENCH ||
detType == slsDetectorDefs::GOTTHARD2) {
// show gain plot // show gain plot
if (gaindest != NULL) { if (gaindest != NULL) {
for (ichan = 0; ichan < size; ++ichan) { for (ichan = 0; ichan < size; ++ichan) {
uint16_t temp = (*((u_int16_t *)source)); uint16_t temp = (*((u_int16_t *)source));
gaindest[ichan] = ((temp & 0xC000) >> 14); gaindest[ichan] = ((temp & 0xC000) >> 14);
dest[ichan] = (temp & 0x3FFF); dest[ichan] = (temp & pixelMask);
source += 2; source += 2;
} }
} }
@ -918,7 +934,7 @@ void qDrawPlot::toDoublePixelData(double *dest, char *source, int size, int data
// only data plot // only data plot
else { else {
for (ichan = 0; ichan < size; ++ichan) { for (ichan = 0; ichan < size; ++ichan) {
dest[ichan] = ((*((u_int16_t *)source)) & 0x3FFF); dest[ichan] = ((*((u_int16_t *)source)) & pixelMask);
source += 2; source += 2;
} }
} }

View File

@ -30,6 +30,7 @@ void qTabAdvanced::SetupWidgetWindow() {
tab_roi->setEnabled(true); tab_roi->setEnabled(true);
break; break;
case slsDetectorDefs::MYTHEN3: case slsDetectorDefs::MYTHEN3:
case slsDetectorDefs::GOTTHARD2:
lblDiscardBits->setEnabled(true); lblDiscardBits->setEnabled(true);
spinDiscardBits->setEnabled(true); spinDiscardBits->setEnabled(true);
default: default:
@ -361,7 +362,7 @@ void qTabAdvanced::SetDetectorUDPIP() {
std::string s = dispDetectorUDPIP->text().toAscii().constData(); std::string s = dispDetectorUDPIP->text().toAscii().constData();
FILE_LOG(logINFO) << "Setting Detector UDP IP:" << s; FILE_LOG(logINFO) << "Setting Detector UDP IP:" << s;
try { try {
det->setSourceUDPIP(s, {comboDetector->currentIndex()}); det->setSourceUDPIP(sls::IpAddr{s}, {comboDetector->currentIndex()});
} CATCH_HANDLE ("Could not set Detector UDP IP.", } CATCH_HANDLE ("Could not set Detector UDP IP.",
"qTabAdvanced::SetDetectorUDPIP", this, "qTabAdvanced::SetDetectorUDPIP", this,
&qTabAdvanced::GetDetectorUDPIP) &qTabAdvanced::GetDetectorUDPIP)
@ -371,7 +372,7 @@ void qTabAdvanced::SetDetectorUDPMAC() {
std::string s = dispDetectorUDPMAC->text().toAscii().constData(); std::string s = dispDetectorUDPMAC->text().toAscii().constData();
FILE_LOG(logINFO) << "Setting Detector UDP MAC:" << s; FILE_LOG(logINFO) << "Setting Detector UDP MAC:" << s;
try { try {
det->setSourceUDPMAC(s, {comboDetector->currentIndex()}); det->setSourceUDPMAC(sls::MacAddr{s}, {comboDetector->currentIndex()});
} CATCH_HANDLE ("Could not set Detector UDP MAC.", } CATCH_HANDLE ("Could not set Detector UDP MAC.",
"qTabAdvanced::SetDetectorUDPMAC", this, "qTabAdvanced::SetDetectorUDPMAC", this,
&qTabAdvanced::GetDetectorUDPMAC) &qTabAdvanced::GetDetectorUDPMAC)
@ -390,7 +391,7 @@ void qTabAdvanced::SetCltZMQIP() {
std::string s = dispZMQIP->text().toAscii().constData(); std::string s = dispZMQIP->text().toAscii().constData();
FILE_LOG(logINFO) << "Setting Client ZMQ IP:" << s; FILE_LOG(logINFO) << "Setting Client ZMQ IP:" << s;
try { try {
det->setClientZmqIp(s, {comboDetector->currentIndex()}); det->setClientZmqIp(sls::IpAddr{s}, {comboDetector->currentIndex()});
} CATCH_HANDLE ("Could not set Client ZMQ IP.", } CATCH_HANDLE ("Could not set Client ZMQ IP.",
"qTabAdvanced::SetCltZMQIP", this, "qTabAdvanced::SetCltZMQIP", this,
&qTabAdvanced::GetCltZMQIP) &qTabAdvanced::GetCltZMQIP)
@ -431,7 +432,7 @@ void qTabAdvanced::SetRxrUDPIP() {
std::string s = dispRxrUDPIP->text().toAscii().constData(); std::string s = dispRxrUDPIP->text().toAscii().constData();
FILE_LOG(logINFO) << "Setting Receiver UDP IP:" << s; FILE_LOG(logINFO) << "Setting Receiver UDP IP:" << s;
try { try {
det->setDestinationUDPIP(s, {comboDetector->currentIndex()}); det->setDestinationUDPIP(sls::IpAddr{s}, {comboDetector->currentIndex()});
} CATCH_HANDLE ("Could not set Receiver UDP IP.", } CATCH_HANDLE ("Could not set Receiver UDP IP.",
"qTabAdvanced::SetRxrUDPIP", this, "qTabAdvanced::SetRxrUDPIP", this,
&qTabAdvanced::GetRxrUDPIP) &qTabAdvanced::GetRxrUDPIP)
@ -441,7 +442,7 @@ void qTabAdvanced::SetRxrUDPMAC() {
std::string s = dispRxrUDPMAC->text().toAscii().constData(); std::string s = dispRxrUDPMAC->text().toAscii().constData();
FILE_LOG(logINFO) << "Setting Receiver UDP MAC:" << s; FILE_LOG(logINFO) << "Setting Receiver UDP MAC:" << s;
try { try {
det->setDestinationUDPMAC(s, {comboDetector->currentIndex()}); det->setDestinationUDPMAC(sls::MacAddr{s}, {comboDetector->currentIndex()});
} CATCH_HANDLE ("Could not set Receiver UDP MAC.", } CATCH_HANDLE ("Could not set Receiver UDP MAC.",
"qTabAdvanced::SetRxrUDPMAC", this, "qTabAdvanced::SetRxrUDPMAC", this,
&qTabAdvanced::GetRxrUDPMAC) &qTabAdvanced::GetRxrUDPMAC)
@ -460,7 +461,7 @@ void qTabAdvanced::SetRxrZMQIP() {
std::string s = dispRxrZMQIP->text().toAscii().constData(); std::string s = dispRxrZMQIP->text().toAscii().constData();
FILE_LOG(logINFO) << "Setting Receiver ZMQ IP:" << s; FILE_LOG(logINFO) << "Setting Receiver ZMQ IP:" << s;
try { try {
det->setRxZmqIP(s, {comboDetector->currentIndex()}); det->setRxZmqIP(sls::IpAddr{s}, {comboDetector->currentIndex()});
} CATCH_HANDLE ("Could not set Receiver ZMQ IP.", } CATCH_HANDLE ("Could not set Receiver ZMQ IP.",
"qTabAdvanced::SetRxrZMQIP", this, "qTabAdvanced::SetRxrZMQIP", this,
&qTabAdvanced::GetRxrZMQIP) &qTabAdvanced::GetRxrZMQIP)

View File

@ -113,6 +113,26 @@ void qTabDeveloper::SetupWidgetWindow() {
dacWidgets.push_back(new qDacWidget(this, det, true, "vtrim: ", getSLSIndex(detType, tempid++))); dacWidgets.push_back(new qDacWidget(this, det, true, "vtrim: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vdcsh: ", getSLSIndex(detType, tempid++))); dacWidgets.push_back(new qDacWidget(this, det, true, "vdcsh: ", getSLSIndex(detType, tempid++)));
break; break;
case slsDetectorDefs::GOTTHARD2:
lblSpinHV->show();
spinHV->show();
hvmin = 0;
dacWidgets.push_back(new qDacWidget(this, det, true, "vref_h_adc: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vb_comp_fe: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vb_comp_adc: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vcom_cds: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vref_rstore: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vb_opa_1st: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vref_comp_fe: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vcom_adc1: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vref_prech: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vref_l_adc: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vref_cds: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vb_cs: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vb_opa_fd: ", getSLSIndex(detType, tempid++)));
dacWidgets.push_back(new qDacWidget(this, det, true, "vcom_adc2: ", getSLSIndex(detType, tempid++)));
break;
default: default:
break; break;
} }
@ -367,6 +387,41 @@ slsDetectorDefs::dacIndex qTabDeveloper::getSLSIndex(slsDetectorDefs::detectorTy
} }
break; break;
case slsDetectorDefs::GOTTHARD2:
switch (index) {
case 0:
return slsDetectorDefs::VREF_H_ADC;
case 1:
return slsDetectorDefs::VB_COMP_FE;
case 2:
return slsDetectorDefs::VB_COMP_ADC;
case 3:
return slsDetectorDefs::VCOM_CDS;
case 4:
return slsDetectorDefs::VREF_RSTORE;
case 5:
return slsDetectorDefs::VB_OPA_1ST;
case 6:
return slsDetectorDefs::VREF_COMP_FE;
case 7:
return slsDetectorDefs::VCOM_ADC1;
case 8:
return slsDetectorDefs::VREF_PRECH;
case 9:
return slsDetectorDefs::VREF_L_ADC;
case 10:
return slsDetectorDefs::VREF_CDS;
case 11:
return slsDetectorDefs::VB_CS;
case 12:
return slsDetectorDefs::VB_OPA_FD;
case 13:
return slsDetectorDefs::VCOM_ADC2;
default:
throw sls::RuntimeError(std::string("Unknown dac/adc index") + std::to_string(index));
}
break;
default: default:
throw sls::RuntimeError(std::string("Unknown detector type")); throw sls::RuntimeError(std::string("Unknown detector type"));
} }

View File

@ -60,6 +60,7 @@ void qTabPlot::SetupWidgetWindow() {
switch(det->getDetectorType().squash()) { switch(det->getDetectorType().squash()) {
case slsDetectorDefs::GOTTHARD: case slsDetectorDefs::GOTTHARD:
case slsDetectorDefs::MYTHEN3: case slsDetectorDefs::MYTHEN3:
case slsDetectorDefs::GOTTHARD2:
is1d = true; is1d = true;
break; break;
case slsDetectorDefs::EIGER: case slsDetectorDefs::EIGER:

View File

@ -83,6 +83,11 @@ void qTabSettings::SetupDetectorSettings() {
item[(int)FORCESWITCHG1]->setEnabled(true); item[(int)FORCESWITCHG1]->setEnabled(true);
item[(int)FORCESWITCHG2]->setEnabled(true); item[(int)FORCESWITCHG2]->setEnabled(true);
break; break;
case slsDetectorDefs::GOTTHARD2:
item[(int)DYNAMICGAIN]->setEnabled(true);
item[(int)FIXGAIN1]->setEnabled(true);
item[(int)FIXGAIN2]->setEnabled(true);
break;
default: default:
FILE_LOG(logDEBUG) << "Unknown detector type. Exiting GUI."; FILE_LOG(logDEBUG) << "Unknown detector type. Exiting GUI.";
qDefs::Message(qDefs::CRITICAL, qDefs::Message(qDefs::CRITICAL,

View File

@ -15,7 +15,7 @@ add_executable(ctbDetectorServer_virtual
../slsDetectorServer/src/INA226.c ../slsDetectorServer/src/INA226.c
../slsDetectorServer/src/LTC2620.c ../slsDetectorServer/src/LTC2620.c
../slsDetectorServer/src/MAX1932.c ../slsDetectorServer/src/MAX1932.c
../slsDetectorServer/src/programfpga.c ../slsDetectorServer/src/programFpgaBlackfin.c
) )
include_directories( include_directories(

View File

@ -12,7 +12,7 @@ DESTDIR ?= bin
INSTMODE = 0777 INSTMODE = 0777
SRCS = slsDetectorFunctionList.c SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)communication_funcs_UDP.c $(main_src)UDPPacketHeaderGenerator.c $(main_src)AD7689.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)I2C.c $(main_src)INA226.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programfpga.c SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)communication_funcs_UDP.c $(main_src)UDPPacketHeaderGenerator.c $(main_src)AD7689.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)I2C.c $(main_src)INA226.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programFpgaBlackfin.c
OBJS = $(SRCS:.c=.o) OBJS = $(SRCS:.c=.o)

View File

@ -12,9 +12,6 @@
#include "INA226.h" // i2c #include "INA226.h" // i2c
#include "ALTERA_PLL.h" // pll #include "ALTERA_PLL.h" // pll
#include "blackfin.h" #include "blackfin.h"
#ifndef VIRTUAL
#include "programfpga.h"
#endif
#include <string.h> #include <string.h>
#include <unistd.h> // usleep #include <unistd.h> // usleep

View File

@ -10,6 +10,7 @@ add_executable(gotthard2DetectorServer_virtual
../slsDetectorServer/src/LTC2620_Driver.c ../slsDetectorServer/src/LTC2620_Driver.c
../slsDetectorServer/src/ALTERA_PLL_CYCLONE10.c ../slsDetectorServer/src/ALTERA_PLL_CYCLONE10.c
../slsDetectorServer/src/ASIC_Driver.c ../slsDetectorServer/src/ASIC_Driver.c
../slsDetectorServer/src/programFpgaNios.c
) )
include_directories( include_directories(

View File

@ -12,7 +12,7 @@ DESTDIR ?= bin
INSTMODE = 0777 INSTMODE = 0777
SRCS = slsDetectorFunctionList.c SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)nios.c $(main_src)common.c $(main_src)DAC6571.c $(main_src)LTC2620_Driver.c $(main_src)ALTERA_PLL_CYCLONE10.c $(main_src)ASIC_Driver.c SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)nios.c $(main_src)common.c $(main_src)DAC6571.c $(main_src)LTC2620_Driver.c $(main_src)ALTERA_PLL_CYCLONE10.c $(main_src)ASIC_Driver.c $(main_src)/programFpgaNios.c
OBJS = $(SRCS:.c=.o) OBJS = $(SRCS:.c=.o)

View File

@ -47,9 +47,6 @@ int injectedChannelsIncrement = 0;
int vetoReference[NCHIP][NCHAN]; int vetoReference[NCHIP][NCHAN];
uint8_t adcConfiguration[NCHIP][NADC]; uint8_t adcConfiguration[NCHIP][NADC];
int burstMode = BURST_INTERNAL; int burstMode = BURST_INTERNAL;
int64_t exptime_ns = 0;
int64_t period_ns = 0;
int64_t nframes = 0;
int detPos[2] = {}; int detPos[2] = {};
int isInitCheckDone() { int isInitCheckDone() {
@ -252,7 +249,7 @@ u_int16_t getHardwareVersionNumber() {
#ifdef VIRTUAL #ifdef VIRTUAL
return 0; return 0;
#endif #endif
return ((bus_r(MCB_SERIAL_NO_REG)));// & HARDWARE_VERSION_NUM_MSK) >> HARDWARE_VERSION_NUM_OFST); return ((bus_r(MCB_SERIAL_NO_REG) & MCB_SERIAL_NO_VRSN_MSK) >> MCB_SERIAL_NO_VRSN_OFST);
} }
u_int32_t getDetectorNumber(){ u_int32_t getDetectorNumber(){
@ -314,10 +311,14 @@ u_int32_t getDetectorIP(){
/* initialization */ /* initialization */
void initControlServer(){ void initControlServer(){
CreateNotificationForCriticalTasks();
if (initError == OK) { if (initError == OK) {
setupDetector(); setupDetector();
} }
initCheckDone = 1; initCheckDone = 1;
if (initError == OK) {
NotifyServerStartSuccess();
}
} }
void initStopServer() { void initStopServer() {
@ -349,9 +350,6 @@ void setupDetector() {
injectedChannelsOffset = 0; injectedChannelsOffset = 0;
injectedChannelsIncrement = 0; injectedChannelsIncrement = 0;
burstMode = BURST_INTERNAL; burstMode = BURST_INTERNAL;
exptime_ns = 0;
period_ns = 0;
nframes = 0;
{ {
int i, j; int i, j;
for (i = 0; i < NUM_CLOCKS; ++i) { for (i = 0; i < NUM_CLOCKS; ++i) {
@ -447,10 +445,15 @@ int readConfigFile() {
return initError; return initError;
} }
// require a sleep before and after the rst dac signal
usleep (INITIAL_STARTUP_WAIT);
// inform FPGA that onchip dacs will be configured soon // inform FPGA that onchip dacs will be configured soon
FILE_LOG(logINFO, ("Setting configuration starting bit\n")); FILE_LOG(logINFO, ("Setting configuration starting bit\n"));
bus_w(ASIC_CONFIG_REG, bus_r(ASIC_CONFIG_REG) | ASIC_CONFIG_RST_DAC_MSK); bus_w(ASIC_CONFIG_REG, bus_r(ASIC_CONFIG_REG) | ASIC_CONFIG_RST_DAC_MSK);
usleep (INITIAL_STARTUP_WAIT);
FILE* fd = fopen(CONFIG_FILE, "r"); FILE* fd = fopen(CONFIG_FILE, "r");
if(fd == NULL) { if(fd == NULL) {
sprintf(initErrorMessage, "Could not open on-board detector server config file [%s].\n", CONFIG_FILE); sprintf(initErrorMessage, "Could not open on-board detector server config file [%s].\n", CONFIG_FILE);
@ -723,12 +726,23 @@ int setDynamicRange(int dr){
void setNumFrames(int64_t val) { void setNumFrames(int64_t val) {
if (val > 0) { if (val > 0) {
FILE_LOG(logINFO, ("Setting number of frames %lld [local]\n", (long long int)val)); FILE_LOG(logINFO, ("Setting number of frames %lld [local]\n", (long long int)val));
nframes = val; // continuous mode
if (burstMode == BURST_OFF) {
setNumFramesCont(val);
setNumFramesBurst(1);
} else {
setNumFramesBurst(val);
setNumFramesCont(1);
}
} }
} }
int64_t getNumFrames() { int64_t getNumFrames() {
return nframes; if (burstMode == BURST_OFF) {
return getNumFramesCont();
} else {
return getNumFramesBurst();
}
} }
void setNumTriggers(int64_t val) { void setNumTriggers(int64_t val) {
@ -748,12 +762,16 @@ int setExpTime(int64_t val) {
return FAIL; return FAIL;
} }
FILE_LOG(logINFO, ("Setting exptime %lld ns [local]\n", (long long int)val)); FILE_LOG(logINFO, ("Setting exptime %lld ns [local]\n", (long long int)val));
exptime_ns = val; // continuous mode
return OK; if (burstMode == BURST_OFF) {
return setExptimeCont(val);
} else {
return setExptimeBurst(val);
}
} }
int64_t getExpTime() { int64_t getExpTime() {
return exptime_ns; return getExptimeBoth();
} }
int setPeriod(int64_t val) { int setPeriod(int64_t val) {
@ -762,12 +780,22 @@ int setPeriod(int64_t val) {
return FAIL; return FAIL;
} }
FILE_LOG(logINFO, ("Setting period %lld ns [local]\n", (long long int)val)); FILE_LOG(logINFO, ("Setting period %lld ns [local]\n", (long long int)val));
period_ns = val; // continuous mode
return OK; if (burstMode == BURST_OFF) {
setPeriodBurst(0);
return setPeriodCont(val);
} else {
setPeriodCont(0);
return setPeriodBurst(val);
}
} }
int64_t getPeriod() { int64_t getPeriod() {
return period_ns; if (burstMode == BURST_OFF) {
return getPeriodCont();
} else {
return getPeriodBurst();
}
} }
void setNumFramesBurst(int64_t val) { void setNumFramesBurst(int64_t val) {
@ -832,6 +860,7 @@ int setPeriodBurst(int64_t val) {
} }
int64_t getPeriodBurst() { int64_t getPeriodBurst() {
FILE_LOG(logDEBUG, ("Getting period [Burst mode]\n"));
return get64BitReg(ASIC_INT_PERIOD_LSB_REG, ASIC_INT_PERIOD_MSB_REG)/ (1E-9 * clkFrequency[SYSTEM_C0]); return get64BitReg(ASIC_INT_PERIOD_LSB_REG, ASIC_INT_PERIOD_MSB_REG)/ (1E-9 * clkFrequency[SYSTEM_C0]);
} }
@ -850,6 +879,7 @@ int setPeriodCont(int64_t val) {
} }
int64_t getPeriodCont() { int64_t getPeriodCont() {
FILE_LOG(logDEBUG, ("Getting period [Continuous mode]\n"));
return get64BitReg(SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/ (1E-9 * FIXED_PLL_FREQUENCY); return get64BitReg(SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/ (1E-9 * FIXED_PLL_FREQUENCY);
} }
@ -1820,84 +1850,24 @@ enum burstMode getBurstMode() {
int runmode = bus_r (addr) & ASIC_CONFIG_RUN_MODE_MSK; int runmode = bus_r (addr) & ASIC_CONFIG_RUN_MODE_MSK;
switch (runmode) { switch (runmode) {
case ASIC_CONFIG_RUN_MODE_CONT_VAL: case ASIC_CONFIG_RUN_MODE_CONT_VAL:
return BURST_OFF; burstMode = BURST_OFF;
break;
case ASIC_CONFIG_RUN_MODE_INT_BURST_VAL: case ASIC_CONFIG_RUN_MODE_INT_BURST_VAL:
return BURST_INTERNAL; burstMode = BURST_INTERNAL;
break;
case ASIC_CONFIG_RUN_MODE_EXT_BURST_VAL: case ASIC_CONFIG_RUN_MODE_EXT_BURST_VAL:
return BURST_EXTERNAL; burstMode = BURST_EXTERNAL;
break;
default: default:
FILE_LOG(logERROR, ("Unknown run mode read from FPGA %d\n", runmode)); FILE_LOG(logERROR, ("Unknown run mode read from FPGA %d\n", runmode));
return -1; return -1;
} }
return burstMode;
} }
/* aquisition */ /* aquisition */
int updateAcquisitionRegisters(char* mess) {
// burst mode
if (burstMode != BURST_OFF) {
// validate #frames in burst mode
if (nframes > MAX_FRAMES_IN_BURST_MODE) {
sprintf(mess, "Could not start acquisition because number of frames %lld must be <= %d in burst mode.\n", (long long unsigned int)nframes, MAX_FRAMES_IN_BURST_MODE);
FILE_LOG(logERROR,(mess));
return FAIL;
}
setNumFramesBurst(nframes);
// exptime
if (setExptimeBurst(exptime_ns) == FAIL) {
sprintf(mess, "Could not start acquisition because exptime could not be set in burst mode. Set %lld ns, got %lld ns.\n", (long long unsigned int)exptime_ns, getExptimeBoth());
FILE_LOG(logERROR,(mess));
return FAIL;
}
// period
if (setPeriodBurst(period_ns) == FAIL) {
sprintf(mess, "Could not start acquisition because period could not be set in burst mode. Set %lld ns, got %lld ns.\n", (long long unsigned int)period_ns, getPeriodBurst());
FILE_LOG(logERROR,(mess));
return FAIL;
}
// set continuous values to default (exptime same register)
FILE_LOG(logINFO, ("Setting continuous mode registers to defaults\n"));
// frames
setNumFramesCont(1);
// period
if (setPeriodCont(0) == FAIL) {
sprintf(mess, "Could not start acquisition because period could not be set in continuous mode. Set 0 ns, got %lld ns.\n", getPeriodCont());
FILE_LOG(logERROR,(mess));
return FAIL;
}
}
// continuous
else {
// frames
setNumFramesCont(nframes);
// exptime
if (setExptimeCont(exptime_ns) == FAIL) {
sprintf(mess, "Could not start acquisition because exptime could not be set in continuous mode. Set %lld ns, got %lld ns.\n", (long long unsigned int)exptime_ns, getExptimeBoth());
FILE_LOG(logERROR,(mess));
return FAIL;
}
// period
if (setPeriodCont(period_ns) == FAIL) {
sprintf(mess, "Could not start acquisition because period could not be set in continuous mode. Set %lld ns, got %lld ns.\n", (long long unsigned int)period_ns, getPeriodCont());
FILE_LOG(logERROR,(mess));
return FAIL;
}
// set burst values to default (exptime same register)
FILE_LOG(logINFO, ("Setting burst mode registers to defaults\n"));
setNumFramesBurst(1);
// period
if (setPeriodBurst(0) == FAIL) {
sprintf(mess, "Could not start acquisition because period could not be set in burst mode. Set 0 ns, got %lld ns.\n", getPeriodBurst());
FILE_LOG(logERROR,(mess));
return FAIL;
}
}
return OK;
}
int startStateMachine(){ int startStateMachine(){
#ifdef VIRTUAL #ifdef VIRTUAL
// create udp socket // create udp socket

View File

@ -27,13 +27,14 @@
#define TYPE_GOTTHARD2_MODULE_VAL (512) #define TYPE_GOTTHARD2_MODULE_VAL (512)
#define TYPE_TOLERANCE (10) #define TYPE_TOLERANCE (10)
#define TYPE_NO_MODULE_STARTING_VAL (800) #define TYPE_NO_MODULE_STARTING_VAL (800)
#define INITIAL_STARTUP_WAIT (1 * 1000 * 1000)
/** Default Parameters */ /** Default Parameters */
#define DEFAULT_BURST_MODE (BURST_INTERNAL) #define DEFAULT_BURST_MODE (BURST_INTERNAL)
#define DEFAULT_NUM_FRAMES (1) #define DEFAULT_NUM_FRAMES (1)
#define DEFAULT_NUM_CYCLES (1) #define DEFAULT_NUM_CYCLES (1)
#define DEFAULT_EXPTIME (1 * 1000 * 1000) // 1 ms #define DEFAULT_EXPTIME (0) // 0 ms (220ns in firmware)
#define DEFAULT_PERIOD (1 * 1000 * 1000 * 1000) // 1 s #define DEFAULT_PERIOD (0) // 0 ms
#define DEFAULT_DELAY_AFTER_TRIGGER (0) #define DEFAULT_DELAY_AFTER_TRIGGER (0)
#define DEFAULT_HIGH_VOLTAGE (0) #define DEFAULT_HIGH_VOLTAGE (0)
#define DEFAULT_TIMING_MODE (AUTO_TIMING) #define DEFAULT_TIMING_MODE (AUTO_TIMING)

View File

@ -10,7 +10,7 @@ add_executable(jungfrauDetectorServer_virtual
../slsDetectorServer/src/ALTERA_PLL.c ../slsDetectorServer/src/ALTERA_PLL.c
../slsDetectorServer/src/LTC2620.c ../slsDetectorServer/src/LTC2620.c
../slsDetectorServer/src/MAX1932.c ../slsDetectorServer/src/MAX1932.c
../slsDetectorServer/src/programfpga.c ../slsDetectorServer/src/programFpgaBlackfin.c
../slsDetectorServer/src/communication_funcs_UDP.c ../slsDetectorServer/src/communication_funcs_UDP.c
) )
@ -28,7 +28,7 @@ target_compile_definitions(jungfrauDetectorServer_virtual
) )
target_link_libraries(jungfrauDetectorServer_virtual target_link_libraries(jungfrauDetectorServer_virtual
PUBLIC pthread rt PUBLIC pthread rt slsProjectOptions slsProjectWarnings
) )
set_target_properties(jungfrauDetectorServer_virtual PROPERTIES set_target_properties(jungfrauDetectorServer_virtual PROPERTIES

View File

@ -12,7 +12,7 @@ DESTDIR ?= bin
INSTMODE = 0777 INSTMODE = 0777
SRCS = slsDetectorFunctionList.c SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programfpga.c SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programFpgaBlackfin.c
OBJS = $(SRCS:.c=.o) OBJS = $(SRCS:.c=.o)

View File

@ -8,9 +8,7 @@
#include "ALTERA_PLL.h" // pll #include "ALTERA_PLL.h" // pll
#include "blackfin.h" #include "blackfin.h"
#include "common.h" #include "common.h"
#ifndef VIRTUAL #ifdef VIRTUAL
#include "programfpga.h"
#else
#include "communication_funcs_UDP.h" #include "communication_funcs_UDP.h"
#endif #endif
@ -67,7 +65,6 @@ void basictests() {
} }
return; return;
#else #else
defineGPIOpins(); defineGPIOpins();
resetFPGA(); resetFPGA();
if (mapCSP0() == FAIL) { if (mapCSP0() == FAIL) {

View File

@ -12,7 +12,7 @@ add_executable(moenchDetectorServer_virtual
../slsDetectorServer/src/ALTERA_PLL.c ../slsDetectorServer/src/ALTERA_PLL.c
../slsDetectorServer/src/LTC2620.c ../slsDetectorServer/src/LTC2620.c
../slsDetectorServer/src/MAX1932.c ../slsDetectorServer/src/MAX1932.c
../slsDetectorServer/src/programfpga.c ../slsDetectorServer/src/programFpgaBlackfin.c
) )
include_directories( include_directories(

View File

@ -12,7 +12,7 @@ DESTDIR ?= bin
INSTMODE = 0777 INSTMODE = 0777
SRCS = slsDetectorFunctionList.c SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)communication_funcs_UDP.c $(main_src)UDPPacketHeaderGenerator.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programfpga.c SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)communication_funcs_UDP.c $(main_src)UDPPacketHeaderGenerator.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programFpgaBlackfin.c
OBJS = $(SRCS:.c=.o) OBJS = $(SRCS:.c=.o)

View File

@ -10,7 +10,7 @@
#include "ALTERA_PLL.h" // pll #include "ALTERA_PLL.h" // pll
#include "blackfin.h" #include "blackfin.h"
#ifndef VIRTUAL #ifndef VIRTUAL
#include "programfpga.h" #include "programFpgaBlackfin.h"
#endif #endif
#include <string.h> #include <string.h>

View File

@ -9,6 +9,7 @@ add_executable(mythen3DetectorServer_virtual
../slsDetectorServer/src/common.c ../slsDetectorServer/src/common.c
../slsDetectorServer/src/LTC2620_Driver.c ../slsDetectorServer/src/LTC2620_Driver.c
../slsDetectorServer/src/ALTERA_PLL_CYCLONE10.c ../slsDetectorServer/src/ALTERA_PLL_CYCLONE10.c
../slsDetectorServer/src/programFpgaNios.c
) )
include_directories( include_directories(

View File

@ -12,7 +12,7 @@ DESTDIR ?= bin
INSTMODE = 0777 INSTMODE = 0777
SRCS = slsDetectorFunctionList.c SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)nios.c $(main_src)DAC6571.c $(main_src)common.c $(main_src)LTC2620_Driver.c $(main_src)ALTERA_PLL_CYCLONE10.c SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)nios.c $(main_src)DAC6571.c $(main_src)common.c $(main_src)LTC2620_Driver.c $(main_src)ALTERA_PLL_CYCLONE10.c $(main_src)/programFpgaNios.c
OBJS = $(SRCS:.c=.o) OBJS = $(SRCS:.c=.o)

View File

@ -249,7 +249,7 @@ u_int32_t getDetectorNumber(){
#ifdef VIRTUAL #ifdef VIRTUAL
return 0; return 0;
#endif #endif
return bus_r(MCB_SERIAL_NO_REG); return ((bus_r(MCB_SERIAL_NO_REG) & MCB_SERIAL_NO_VRSN_MSK) >> MCB_SERIAL_NO_VRSN_OFST);
} }
@ -303,10 +303,14 @@ u_int32_t getDetectorIP(){
/* initialization */ /* initialization */
void initControlServer(){ void initControlServer(){
CreateNotificationForCriticalTasks();
if (initError == OK) { if (initError == OK) {
setupDetector(); setupDetector();
} }
initCheckDone = 1; initCheckDone = 1;
if (initError == OK) {
NotifyServerStartSuccess();
}
} }
void initStopServer() { void initStopServer() {

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <stdio.h> #include <stdio.h>
#include <stdint.h>
/** /**
* Define GPIO pins if not defined * Define GPIO pins if not defined
@ -49,4 +50,4 @@ void stopWritingFPGAprogram(FILE* filefp);
* @param filefp pointer to flash * @param filefp pointer to flash
* @return 0 for success, 1 for fail (cannot write) * @return 0 for success, 1 for fail (cannot write)
*/ */
int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); int writeFPGAProgram(char* fpgasrc, uint64_t fsize, FILE* filefp);

View File

@ -0,0 +1,48 @@
#pragma once
#include <stdio.h>
#include <stdint.h>
#define NIOS_MAX_APP_IMAGE_SIZE (0x00580000)
/** Notify microcontroller of successful server start up */
void NotifyServerStartSuccess();
/** create notification file to notify watchdog of critical tasks (to not shutdown) */
void CreateNotificationForCriticalTasks();
/** write 1 to notification file to postpone shut down process if requested*/
void NotifyCriticalTask();
/** write 0 to notification file to allow shut down process if requested */
void NotifyCriticalTaskDone();
/** reset fpga and controller(only implemented for >= v1.1 boards) */
void rebootControllerAndFPGA();
/** finds the right mtd drive
* @param mess error message
* @returns ok or fail
*/
int findFlash(char* mess);
/** erase flash */
void eraseFlash();
/** erase and write flash
* @param mess error message
* @param fpgasrc program source
* @param fsize file size
* @returns ok or fail
*/
int eraseAndWriteToFlash(char* mess, char* fpgasrc, uint64_t fsize);
/**
* Write FPGA Program to flash
* @param mess error message
* @param fpgasrc source program
* @param fsize size of program
* @param filefp pointer to flash
* @return ok or fail
*/
int writeFPGAProgram(char* mess, char* fpgasrc, uint64_t fsize, FILE* filefp);

View File

@ -366,10 +366,10 @@ int getFrequency(enum CLKINDEX ind);
void configureSyncFrequency(enum CLKINDEX ind); void configureSyncFrequency(enum CLKINDEX ind);
void setPipeline(enum CLKINDEX ind, int val); void setPipeline(enum CLKINDEX ind, int val);
int getPipeline(enum CLKINDEX ind); int getPipeline(enum CLKINDEX ind);
extern void eraseFlash(); // programfpga.h extern void eraseFlash(); // programFpgaBlackfin.h
extern int startWritingFPGAprogram(FILE** filefp); // programfpga.h extern int startWritingFPGAprogram(FILE** filefp); // programFpgaBlackfin.h
extern void stopWritingFPGAprogram(FILE* filefp); // programfpga.h extern void stopWritingFPGAprogram(FILE* filefp); // programFpgaBlackfin.h
extern int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); // programfpga.h extern int writeFPGAProgram(char* fpgasrc, uint64_t fsize, FILE* filefp); // programFpgaBlackfin.h
// patterns // patterns
uint64_t writePatternIOControl(uint64_t word); uint64_t writePatternIOControl(uint64_t word);
uint64_t writePatternClkControl(uint64_t word); uint64_t writePatternClkControl(uint64_t word);
@ -401,10 +401,10 @@ int validatePhaseinDegrees(enum CLKINDEX ind, int val, int retval);
int setThresholdTemperature(int val); int setThresholdTemperature(int val);
int setTemperatureControl(int val); int setTemperatureControl(int val);
int setTemperatureEvent(int val); int setTemperatureEvent(int val);
extern void eraseFlash(); // programfpga.h extern void eraseFlash(); // programFpgaBlackfin.h
extern int startWritingFPGAprogram(FILE** filefp); // programfpga.h extern int startWritingFPGAprogram(FILE** filefp); // programFpgaBlackfin.h
extern void stopWritingFPGAprogram(FILE* filefp); // programfpga.h extern void stopWritingFPGAprogram(FILE* filefp); // programFpgaBlackfin.h
extern int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); // programfpga.h extern int writeFPGAProgram(char* fpgasrc, uint64_t fsize, FILE* filefp); // programFpgaBlackfin.h
void alignDeserializer(); void alignDeserializer();
// eiger specific - iodelay, pulse, rate, temp, activate, delay nw parameter // eiger specific - iodelay, pulse, rate, temp, activate, delay nw parameter
@ -480,7 +480,15 @@ enum burstMode getBurstMode();
#endif #endif
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
extern void NotifyServerStartSuccess();
extern void CreateNotificationForCriticalTasks();
extern void rebootControllerAndFPGA(); // programFpgaNios.h
extern int findFlash(char* mess); // programFpgaNios.h
extern void eraseFlash(); // programFpgaNios.h
extern int eraseAndWriteToFlash(char* mess, char* fpgasrc, uint64_t fsize); // programFpgaNios.h
extern int writeFPGAProgram(char* mess, char* fpgasrc, uint64_t fsize, FILE* filefp); // programFpgaNios.h
#endif
#if defined(JUNGFRAUD) || defined(EIGERD) #if defined(JUNGFRAUD) || defined(EIGERD)
@ -500,9 +508,6 @@ int setTransmissionDelayRight(int value);
// aquisition // aquisition
#ifdef GOTTHARD2D
int updateAcquisitionRegisters(char* mess);
#endif
#ifdef EIGERD #ifdef EIGERD
int prepareAcquisition(); int prepareAcquisition();
#endif #endif

View File

@ -19,7 +19,9 @@ void validate(int arg, int retval, char* modename, enum numberMode nummode);
void validate64(int64_t arg, int64_t retval, char* modename, enum numberMode nummode); void validate64(int64_t arg, int64_t retval, char* modename, enum numberMode nummode);
int executeCommand(char* command, char* result, enum TLogLevel level); int executeCommand(char* command, char* result, enum TLogLevel level);
int M_nofunc(int); int M_nofunc(int);
int M_nofuncMode(int); #if defined(MYTHEN3D) || defined(GOTTHARD2D)
extern void rebootControllerAndFPGA();
#endif
// functions called by client // functions called by client
int exec_command(int); int exec_command(int);

View File

@ -28,14 +28,14 @@ void ASIC_Driver_SetDefines(char* driverfname) {
int ASIC_Driver_Set (int index, int length, char* buffer) { int ASIC_Driver_Set (int index, int length, char* buffer) {
char fname[MAX_STR_LENGTH]; char fname[MAX_STR_LENGTH];
sprintf(fname, "%s%d", ASIC_Driver_DriverFileName, index + 1); sprintf(fname, "%s%d", ASIC_Driver_DriverFileName, index + 1);
FILE_LOG(logDEBUG1, ("\t[chip index: %d, length: %d, fname: %s]\n", index, length, fname)); FILE_LOG(logDEBUG2, ("\t[chip index: %d, length: %d, fname: %s]\n", index, length, fname));
{ {
FILE_LOG(logDEBUG1, ("\t[values: \n")); FILE_LOG(logDEBUG2, ("\t[values: \n"));
int i; int i;
for (i = 0; i < length; ++i) { for (i = 0; i < length; ++i) {
FILE_LOG(logDEBUG1, ("\t%d: 0x%02hhx\n", i, buffer[i])); FILE_LOG(logDEBUG2, ("\t%d: 0x%02hhx\n", i, buffer[i]));
} }
FILE_LOG(logDEBUG1, ("\t]\n")); FILE_LOG(logDEBUG2, ("\t]\n"));
} }
#ifdef VIRTUAL #ifdef VIRTUAL

View File

@ -252,8 +252,9 @@ void closeConnection(int file_des) {
} }
void exitServer(int socketDescriptor) { void exitServer(int socketDescriptor) {
if (socketDescriptor >= 0) if (socketDescriptor >= 0) {
close(socketDescriptor); close(socketDescriptor);
}
FILE_LOG(logINFO, ("Closing %s server\n", (isControlServer ? "control":"stop"))); FILE_LOG(logINFO, ("Closing %s server\n", (isControlServer ? "control":"stop")));
FD_CLR(socketDescriptor, &readset); FD_CLR(socketDescriptor, &readset);
isock--; isock--;

View File

@ -1,4 +1,4 @@
#include "programfpga.h" #include "programFpgaBlackfin.h"
#include "ansi.h" #include "ansi.h"
#include "clogger.h" #include "clogger.h"
#include "slsDetectorServer_defs.h" #include "slsDetectorServer_defs.h"
@ -57,6 +57,12 @@ int startWritingFPGAprogram(FILE** filefp){
FILE_LOG(logDEBUG1, ("Start Writing of FPGA program\n")); FILE_LOG(logDEBUG1, ("Start Writing of FPGA program\n"));
//getting the drive //getting the drive
//root:/> cat /proc/mtd
//dev: size erasesize name
//mtd0: 00040000 00020000 "bootloader(nor)"
//mtd1: 00100000 00020000 "linux kernel(nor)"
//mtd2: 002c0000 00020000 "file system(nor)"
//mtd3: 01000000 00010000 "bitfile(spi)"
char output[255]; char output[255];
memset(output, 0, 255); memset(output, 0, 255);
FILE* fp = popen("awk \'$4== \"\\\"bitfile(spi)\\\"\" {print $1}\' /proc/mtd", "r"); FILE* fp = popen("awk \'$4== \"\\\"bitfile(spi)\\\"\" {print $1}\' /proc/mtd", "r");
@ -120,14 +126,14 @@ void stopWritingFPGAprogram(FILE* filefp){
FILE_LOG(logINFO, ("FPGA has picked up the program from flash\n")); FILE_LOG(logINFO, ("FPGA has picked up the program from flash\n"));
} }
int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp){ int writeFPGAProgram(char* fpgasrc, uint64_t fsize, FILE* filefp){
FILE_LOG(logDEBUG1, ("Writing of FPGA Program\n" FILE_LOG(logDEBUG1, ("Writing of FPGA Program\n"
"\taddress of fpgasrc:%p\n" "\taddress of fpgasrc:%p\n"
"\tfsize:%lu\n\tpointer:%p\n", "\tfsize:%llu\n\tpointer:%p\n",
(void *)fpgasrc, fsize, (void*)filefp)); (void *)fpgasrc, (long long unsigned int)fsize, (void*)filefp));
if(fwrite((void*)fpgasrc , sizeof(char) , fsize , filefp )!= fsize){ if(fwrite((void*)fpgasrc , sizeof(char) , fsize , filefp )!= fsize){
FILE_LOG(logERROR, ("Could not write FPGA source to flash (size:%lu)\n", fsize)); FILE_LOG(logERROR, ("Could not write FPGA source to flash (size:%llu)\n", (long long unsigned int)fsize));
return 1; return 1;
} }
FILE_LOG(logDEBUG1, ("program written to flash\n")); FILE_LOG(logDEBUG1, ("program written to flash\n"));

View File

@ -0,0 +1,152 @@
#include "programFpgaNios.h"
#include "ansi.h"
#include "clogger.h"
#include "slsDetectorServer_defs.h"
#include <unistd.h> // usleep
#include <string.h>
/* global variables */
#define MTDSIZE 10
char mtdvalue[MTDSIZE] = {0};
#define NOTIFICATION_FILE "/tmp/block_shutdown"
#define MICROCONTROLLER_FILE "/dev/ttyAL0"
void NotifyServerStartSuccess() {
FILE_LOG(logINFOBLUE, ("Server started successfully\n"));
char command[255];
memset(command, 0, 255);
sprintf(command,"echo r > %s",MICROCONTROLLER_FILE);
system(command);
}
void CreateNotificationForCriticalTasks() {
FILE* fd = fopen(NOTIFICATION_FILE, "r");
if (fd == NULL) {
fd = fopen(NOTIFICATION_FILE, "w");
if (fd == NULL) {
FILE_LOG(logERROR, ("Could not create notication file: %s\n", NOTIFICATION_FILE));
return;
}
FILE_LOG(logINFOBLUE, ("Created notification file: %s\n", NOTIFICATION_FILE));
}
fclose(fd);
NotifyCriticalTaskDone();
}
void NotifyCriticalTask() {
FILE_LOG(logINFO, ("\tNotifying Critical Task Ongoing\n"));
char command[255];
memset(command, 0, 255);
sprintf(command,"echo 1 > %s",NOTIFICATION_FILE);
system(command);
}
void NotifyCriticalTaskDone() {
FILE_LOG(logINFO, ("\tNotifying Critical Task Done\n"));
char command[255];
memset(command, 0, 255);
sprintf(command,"echo 0 > %s",NOTIFICATION_FILE);
system(command);
}
void rebootControllerAndFPGA() {
FILE_LOG(logDEBUG1, ("Reseting FPGA...\n"));
char command[255];
memset(command, 0, 255);
sprintf(command,"echo z > %s",MICROCONTROLLER_FILE);
system(command);
}
int findFlash(char* mess) {
FILE_LOG(logDEBUG1, ("Finding flash drive...\n"));
//getting the drive
// # cat /proc/mtd
// dev: size erasesize name
// mtd0: 00580000 00010000 "qspi BootInfo + Factory Image"
// mtd1: 00580000 00010000 "qspi Application Image"
// mtd2: 00800000 00010000 "qspi Linux Kernel with initramfs"
// mtd3: 00800000 00010000 "qspi Linux Kernel with initramfs Backup"
// mtd4: 02500000 00010000 "qspi ubi filesystem"
// mtd5: 04000000 00010000 "qspi Complete Flash"
char output[255];
memset(output, 0, 255);
FILE* fp = popen("awk \'$5== \"Application\" {print $1}\' /proc/mtd", "r");
if (fp == NULL) {
strcpy(mess, "popen returned NULL. Need that to get mtd drive.\n");
FILE_LOG(logERROR, (mess));
return RO_TRIGGER_IN_FALLING_EDGE;
}
if (fgets(output, sizeof(output), fp) == NULL) {
strcpy(mess, "fgets returned NULL. Need that to get mtd drive.\n");
FILE_LOG(logERROR, (mess));
return FAIL;
}
pclose(fp);
memset(mtdvalue, 0, MTDSIZE);
strcpy(mtdvalue, "/dev/");
char* pch = strtok(output, ":");
if (pch == NULL){
strcpy (mess, "Could not get mtd value\n");
FILE_LOG(logERROR, (mess));
return FAIL;
}
strcat(mtdvalue, pch);
FILE_LOG(logINFO, ("\tFlash drive found: %s\n", mtdvalue));
return OK;
}
void eraseFlash() {
FILE_LOG(logDEBUG1, ("Erasing Flash...\n"));
char command[255];
memset(command, 0, 255);
sprintf(command,"flash_erase %s 0 0",mtdvalue);
system(command);
FILE_LOG(logINFO, ("\tFlash erased\n"));
}
int eraseAndWriteToFlash(char* mess, char* fpgasrc, uint64_t fsize) {
if (findFlash(mess) == FAIL) {
return FAIL;
}
NotifyCriticalTask();
eraseFlash();
// open file pointer to flash
FILE *filefp = fopen(mtdvalue, "w");
if(filefp == NULL){
NotifyCriticalTaskDone();
sprintf (mess, "Unable to open %s in write mode\n", mtdvalue);
FILE_LOG(logERROR, (mess));
return FAIL;
}
FILE_LOG(logINFO, ("\tFlash ready for writing\n"));
// write to flash
if (writeFPGAProgram(mess, fpgasrc, fsize, filefp) == FAIL) {
NotifyCriticalTaskDone();
fclose(filefp);
return FAIL;
}
fclose(filefp);
NotifyCriticalTaskDone();
return OK;
}
int writeFPGAProgram(char* mess, char* fpgasrc, uint64_t fsize, FILE* filefp) {
FILE_LOG(logDEBUG1, ("Writing to flash...\n"
"\taddress of fpgasrc:%p\n"
"\tfsize:%lu\n\tpointer:%p\n",
(void *)fpgasrc, fsize, (void*)filefp));
uint64_t retval = fwrite((void*)fpgasrc , sizeof(char) , fsize , filefp);
if (retval != fsize) {
sprintf (mess, "Could not write FPGA source to flash (size:%llu), write %llu\n", (long long unsigned int) fsize, (long long unsigned int)retval);
FILE_LOG(logERROR, (mess));
return FAIL;
}
FILE_LOG(logINFO, ("\tProgram written to flash\n"));
return OK;
}

View File

@ -10,7 +10,7 @@
#include <signal.h> #include <signal.h>
#include <string.h> #include <string.h>
#include <unistd.h>
// Global variables from communication_funcs // Global variables from communication_funcs
extern int isControlServer; extern int isControlServer;
@ -149,9 +149,13 @@ int main(int argc, char *argv[]){
exitServer(sockfd); exitServer(sockfd);
if (retval == REBOOT) { if (retval == REBOOT) {
FILE_LOG(logINFOBLUE,("Rebooting!\n")); FILE_LOG(logINFORED,("Rebooting!\n"));
fflush(stdout); fflush(stdout);
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
rebootControllerAndFPGA();
#else
system("reboot"); system("reboot");
#endif
} }
FILE_LOG(logINFO,("Goodbye!\n")); FILE_LOG(logINFO,("Goodbye!\n"));
return 0; return 0;

View File

@ -2,6 +2,13 @@
#include "slsDetectorFunctionList.h" #include "slsDetectorFunctionList.h"
#include "communication_funcs.h" #include "communication_funcs.h"
#include "clogger.h" #include "clogger.h"
#ifndef VIRTUAL
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
#include "programFpgaNios.h"
#elif defined(CHIPTESTBOARDD) || defined(JUNGFRAUD) || defined(MOENCHD)
#include "programFpgaBlackfin.h"
#endif
#endif
#include <string.h> #include <string.h>
#include <arpa/inet.h> #include <arpa/inet.h>
@ -594,27 +601,6 @@ int M_nofunc(int file_des) {
} }
// Jungfrau program mode
int M_nofuncMode(int file_des) {
ret = FAIL;
memset(mess, 0, sizeof(mess));
// to receive any arguments
int n = 1;
while (n > 0)
n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER);
sprintf(mess,"This Function %s cannot be executed as the "
"On-board detector server in update mode.\n"
"Restart detector server in normal mode (without any arguments) to continue.\n",
getFunctionName((enum detFuncs)fnum));
FILE_LOG(logERROR, (mess));
return Server_SendResult(file_des, OTHER, NO_UPDATE, NULL, 0);
}
int exec_command(int file_des) { int exec_command(int file_des) {
ret = OK; ret = OK;
memset(mess, 0, sizeof(mess)); memset(mess, 0, sizeof(mess));
@ -1783,12 +1769,6 @@ int start_acquisition(int file_des) {
FILE_LOG(logERROR,(mess)); FILE_LOG(logERROR,(mess));
} }
else else
#endif
#ifdef GOTTHARD2D
if (updateAcquisitionRegisters(mess) == FAIL) {
ret = FAIL;
}
else
#endif #endif
if (configured == FAIL) { if (configured == FAIL) {
ret = FAIL; ret = FAIL;
@ -1919,12 +1899,6 @@ int start_and_read_all(int file_des) {
FILE_LOG(logERROR,(mess)); FILE_LOG(logERROR,(mess));
} }
else else
#endif
#ifdef GOTTHARD2D
if (updateAcquisitionRegisters(mess) == FAIL) {
ret = FAIL;
}
else
#endif #endif
if (configured == FAIL) { if (configured == FAIL) {
ret = FAIL; ret = FAIL;
@ -1991,11 +1965,21 @@ int set_num_frames(int file_des) {
// only set // only set
if (Server_VerifyLock() == OK) { if (Server_VerifyLock() == OK) {
#ifdef GOTTHARD2D
// validate #frames in burst mode
if (getBurstMode() != BURST_OFF && arg > MAX_FRAMES_IN_BURST_MODE) {
ret = FAIL;
sprintf(mess, "Could not set number of frames %lld. Must be <= %d in burst mode.\n", (long long unsigned int)arg, MAX_FRAMES_IN_BURST_MODE);
FILE_LOG(logERROR,(mess));
}
#endif
if (ret == OK) {
setNumFrames(arg); setNumFrames(arg);
int64_t retval = getNumFrames(); int64_t retval = getNumFrames();
FILE_LOG(logDEBUG1, ("retval num frames %lld\n", (long long int)retval)); FILE_LOG(logDEBUG1, ("retval num frames %lld\n", (long long int)retval));
validate64(arg, retval, "set number of frames", DEC); validate64(arg, retval, "set number of frames", DEC);
} }
}
return Server_SendResult(file_des, INT64, UPDATE, NULL, 0); return Server_SendResult(file_des, INT64, UPDATE, NULL, 0);
} }
@ -2587,7 +2571,7 @@ int set_dynamic_range(int file_des) {
#elif EIGERD #elif EIGERD
case 4: case 8: case 16: case 32: case 4: case 8: case 16: case 32:
#endif #endif
#if defined(GOTTHARD) || defined(JUNGFRAU) || defined(CHIPTESTBOARD) || defined(MOENCH) || defined(GOTTHARD2) #if defined(GOTTHARDD) || defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(GOTTHARD2D)
case 16: case 16:
#endif #endif
retval = setDynamicRange(dr); retval = setDynamicRange(dr);
@ -3710,7 +3694,7 @@ int program_fpga(int file_des) {
ret = OK; ret = OK;
memset(mess, 0, sizeof(mess)); memset(mess, 0, sizeof(mess));
#if defined(EIGERD) || defined(GOTTHARDD) || defined(MYTHEN3D) || defined(GOTTHARD2D) #if defined(EIGERD) || defined(GOTTHARDD)
//to receive any arguments //to receive any arguments
int n = 1; int n = 1;
while (n > 0) while (n > 0)
@ -3723,9 +3707,38 @@ int program_fpga(int file_des) {
FILE_LOG(logINFOBLUE, ("Programming FPGA...\n")); FILE_LOG(logINFOBLUE, ("Programming FPGA...\n"));
size_t filesize = 0; #if defined(MYTHEN3D) || defined(GOTTHARD2D)
size_t totalsize = 0; uint64_t filesize = 0;
size_t unitprogramsize = 0; // filesize
if (receiveData(file_des,&filesize,sizeof(filesize),INT64) < 0)
return printSocketReadError();
FILE_LOG(logDEBUG1, ("Total program size is: %llx\n", (long long unsigned int)filesize));
if (filesize > NIOS_MAX_APP_IMAGE_SIZE) {
ret = FAIL;
sprintf(mess,"Could not start programming FPGA. File size 0x%llx exceeds max size 0x%llx. Forgot Compression?\n", (long long unsigned int) filesize, (long long unsigned int)NIOS_MAX_APP_IMAGE_SIZE);
FILE_LOG(logERROR,(mess));
}
Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0);
// receive program
if (ret == OK) {
char* fpgasrc = (char*)malloc(filesize);
if (receiveData(file_des, fpgasrc, filesize, OTHER) < 0)
return printSocketReadError();
ret = eraseAndWriteToFlash(mess, fpgasrc, filesize);
Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0);
//free resources
if (fpgasrc != NULL)
free(fpgasrc);
}
#else // jungfrau, ctb, moench
uint64_t filesize = 0;
uint64_t totalsize = 0;
uint64_t unitprogramsize = 0;
char* fpgasrc = NULL; char* fpgasrc = NULL;
FILE* fp = NULL; FILE* fp = NULL;
@ -3733,7 +3746,7 @@ int program_fpga(int file_des) {
if (receiveData(file_des,&filesize,sizeof(filesize),INT32) < 0) if (receiveData(file_des,&filesize,sizeof(filesize),INT32) < 0)
return printSocketReadError(); return printSocketReadError();
totalsize = filesize; totalsize = filesize;
FILE_LOG(logDEBUG1, ("Total program size is: %d\n", totalsize)); FILE_LOG(logDEBUG1, ("Total program size is: %lld\n", (long long unsigned int)totalsize));
// opening file pointer to flash and telling FPGA to not touch flash // opening file pointer to flash and telling FPGA to not touch flash
@ -3758,7 +3771,7 @@ int program_fpga(int file_des) {
unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb
if (unitprogramsize > filesize) //less than 2mb if (unitprogramsize > filesize) //less than 2mb
unitprogramsize = filesize; unitprogramsize = filesize;
FILE_LOG(logDEBUG1, ("unit size to receive is:%d\nfilesize:%d\n", unitprogramsize, filesize)); FILE_LOG(logDEBUG1, ("unit size to receive is:%lld\nfilesize:%lld\n", (long long unsigned int)unitprogramsize, (long long unsigned int)filesize));
//receive part of program //receive part of program
if (receiveData(file_des,fpgasrc,unitprogramsize,OTHER) < 0) if (receiveData(file_des,fpgasrc,unitprogramsize,OTHER) < 0)
@ -3783,7 +3796,6 @@ int program_fpga(int file_des) {
fflush(stdout); fflush(stdout);
} }
} }
printf("\n");
if (ret == OK) { if (ret == OK) {
FILE_LOG(logINFO, ("Done copying program\n")); FILE_LOG(logINFO, ("Done copying program\n"));
} }
@ -3797,7 +3809,12 @@ int program_fpga(int file_des) {
if (fp != NULL) if (fp != NULL)
fclose(fp); fclose(fp);
FILE_LOG(logINFO, ("Completed program fpga command with %s\n", (ret == OK ? "success" : "fail"))); #endif // end of Blackfin programming
if (ret == FAIL) {
FILE_LOG(logERROR, ("Program FPGA FAIL!\n"));
} else {
FILE_LOG(logINFOGREEN, ("Programming FPGA completed successfully\n"));
}
} }
#endif #endif
#endif #endif
@ -4301,13 +4318,22 @@ int copy_detector_server(int file_des) {
int reboot_controller(int file_des) { int reboot_controller(int file_des) {
ret = OK; ret = OK;
memset(mess, 0, sizeof(mess)); memset(mess, 0, sizeof(mess));
#ifdef EIGERD #if defined(MYTHEN3D) || defined(GOTTHARD2D)
if (getHardwareVersionNumber() == 0) {
ret = FAIL;
strcpy(mess, "Old board version, reboot by yourself please!\n");
FILE_LOG(logINFORED, (mess));
Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0);
return GOODBYE;
}
ret = REBOOT;
#elif EIGERD
functionNotImplemented(); functionNotImplemented();
return ret;
#else #else
FILE_LOG(logINFORED, ("Rebooting controller\n")); ret = REBOOT;
return REBOOT;
#endif #endif
Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0);
return ret;
} }

View File

@ -1,5 +1,5 @@
set(SOURCES set(SOURCES
src/multiSlsDetector.cpp src/DetectorImpl.cpp
src/slsDetectorUsers.cpp src/slsDetectorUsers.cpp
src/slsDetector.cpp src/slsDetector.cpp
src/Detector.cpp src/Detector.cpp
@ -33,6 +33,8 @@ target_link_libraries(slsDetectorShared PUBLIC
slsProjectWarnings slsProjectWarnings
slsSupportLib slsSupportLib
${ZeroMQ_LIBRARIES} ${ZeroMQ_LIBRARIES}
pthread
rt
) )
set(PUBLICHEADERS set(PUBLICHEADERS

View File

@ -5,7 +5,7 @@
#include <memory> #include <memory>
#include <vector> #include <vector>
class multiSlsDetector; class DetectorImpl;
class detectorData; class detectorData;
namespace sls { namespace sls {
@ -23,7 +23,7 @@ void freeSharedMemory(int multiId, int detPos = -1);
* \class Detector * \class Detector
*/ */
class Detector { class Detector {
std::unique_ptr<multiSlsDetector> pimpl; std::unique_ptr<DetectorImpl> pimpl;
public: public:
/** /**
@ -1216,7 +1216,9 @@ class Detector {
* * * *
* ************************************************/ * ************************************************/
/** [Jungfrau][CTB] */ /** [Jungfrau][CTB] fname is a pof file
* [Mythen3][Gotthard2] fname is an rbf file
*/
void programFPGA(const std::string &fname, Positions pos = {}); void programFPGA(const std::string &fname, Positions pos = {});
/** [Jungfrau][CTB] */ /** [Jungfrau][CTB] */
@ -1229,7 +1231,7 @@ class Detector {
void copyDetectorServer(const std::string &fname, void copyDetectorServer(const std::string &fname,
const std::string &hostname, Positions pos = {}); const std::string &hostname, Positions pos = {});
/** [Jungfrau][Gotthard][CTB] */ /** [Jungfrau][Gotthard][CTB][Mythen3][Gotthard2] */
void rebootController(Positions pos = {}); void rebootController(Positions pos = {});
/** /**
@ -1263,6 +1265,12 @@ class Detector {
/** [Gotthard][Jungfrau][CTB] not possible to read back*/ /** [Gotthard][Jungfrau][CTB] not possible to read back*/
void writeAdcRegister(uint32_t addr, uint32_t value, Positions pos = {}); void writeAdcRegister(uint32_t addr, uint32_t value, Positions pos = {});
bool getInitialChecks() const;
/** initial compaibility and other server start up checks
* default enabled */
void setInitialChecks(const bool value);
/************************************************** /**************************************************
* * * *
* Insignificant * * Insignificant *

View File

@ -45,9 +45,7 @@ void CmdParser::Parse(const std::string &s) {
auto old_size = arguments_.size(); auto old_size = arguments_.size();
arguments_.erase(std::remove_if(begin(arguments_), end(arguments_), arguments_.erase(std::remove_if(begin(arguments_), end(arguments_),
[](const std::string &item) { [](const std::string &item) {
if (item == "-h" || item == "--help") return (item == "-h" || item == "--help");
return true;
return false;
}), }),
end(arguments_)); end(arguments_));
if (old_size - arguments_.size() > 0) if (old_size - arguments_.size() > 0)

View File

@ -1288,7 +1288,7 @@ std::string CmdProxy::Counters(int action) {
std::vector <int> result; std::vector <int> result;
for (size_t i = 0; i < 32; ++i) { for (size_t i = 0; i < 32; ++i) {
if (mask & (1 << i)) { if (mask & (1 << i)) {
result.push_back((int)i); result.push_back(static_cast<int>(i));
} }
} }
os << sls::ToString(result) << '\n'; os << sls::ToString(result) << '\n';
@ -1807,7 +1807,8 @@ std::string CmdProxy::ProgramFpga(int action) {
std::ostringstream os; std::ostringstream os;
os << cmd << ' '; os << cmd << ' ';
if (action == defs::HELP_ACTION) { if (action == defs::HELP_ACTION) {
os << "[fname.pof]\n\t[Jungfrau][Ctb] Programs FPGA from pof file." os << "[fname.pof | fname.rbf]\n\t[Jungfrau][Ctb] Programs FPGA from pof file."
<< "\n\t[Mythen3][Gotthard2] Programs FPGA from rbf file."
<< '\n'; << '\n';
} else if (action == defs::GET_ACTION) { } else if (action == defs::GET_ACTION) {
throw sls::RuntimeError("Cannot get"); throw sls::RuntimeError("Cannot get");
@ -1815,9 +1816,6 @@ std::string CmdProxy::ProgramFpga(int action) {
if (args.size() != 1) { if (args.size() != 1) {
WrongNumberOfParameters(1); WrongNumberOfParameters(1);
} }
if (args[0].find(".pof") == std::string::npos) {
throw sls::RuntimeError("Programming file must be a pof file.");
}
det->programFPGA(args[0], {det_id}); det->programFPGA(args[0], {det_id});
os << "successful\n"; os << "successful\n";
} else { } else {
@ -1980,6 +1978,39 @@ std::string CmdProxy::BitOperations(int action) {
return os.str(); return os.str();
} }
std::string CmdProxy::InitialChecks(int action) {
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "[0, 1]\n\tEnable or disable intial compatibility and other checks at detector start up. It is enabled by default. Must come before 'hostname' command to take effect. Can be used to reprogram fpga when current firmware is incompatible."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (det_id != -1) {
throw sls::RuntimeError(
"Cannot enable/disable initial checks at module level");
}
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getInitialChecks();
os << t << '\n';
} else if (action == defs::PUT_ACTION) {
if (det_id != -1) {
throw sls::RuntimeError(
"Cannot get initial checks enable at module level");
}
if (args.size() != 1) {
WrongNumberOfParameters(1);
}
det->setInitialChecks(std::stoi(args[0]));
os << args.front() << '\n';
} else {
throw sls::RuntimeError("Unknown action");
}
return os.str();
}
/* Insignificant */ /* Insignificant */
std::string CmdProxy::ExecuteCommand(int action) { std::string CmdProxy::ExecuteCommand(int action) {

View File

@ -876,6 +876,7 @@ class CmdProxy {
{"getbit", &CmdProxy::BitOperations}, {"getbit", &CmdProxy::BitOperations},
{"firmwaretest", &CmdProxy::firmwaretest}, {"firmwaretest", &CmdProxy::firmwaretest},
{"bustest", &CmdProxy::bustest}, {"bustest", &CmdProxy::bustest},
{"initialchecks", &CmdProxy::InitialChecks},
/* Insignificant */ /* Insignificant */
{"port", &CmdProxy::port}, {"port", &CmdProxy::port},
@ -973,6 +974,7 @@ class CmdProxy {
std::string Register(int action); std::string Register(int action);
std::string AdcRegister(int action); std::string AdcRegister(int action);
std::string BitOperations(int action); std::string BitOperations(int action);
std::string InitialChecks(int action);
/* Insignificant */ /* Insignificant */
std::string ExecuteCommand(int action); std::string ExecuteCommand(int action);
std::string UserDetails(int action); std::string UserDetails(int action);
@ -1009,7 +1011,7 @@ class CmdProxy {
INTEGER_COMMAND_NOID(frames, getNumberOfFrames, setNumberOfFrames, INTEGER_COMMAND_NOID(frames, getNumberOfFrames, setNumberOfFrames,
std::stol, std::stol,
"[n_frames]\n\tNumber of frames per aquire. In trigger mode, number of frames per trigger." "[n_frames]\n\tNumber of frames per aquire. In trigger mode, number of frames per trigger."
"\n\t[Gotthard2] Burst mode has a maximum of 2720 frames. Frames number for both modes are uploaded to detector just before acquisition starts"); "\n\t[Gotthard2] Burst mode has a maximum of 2720 frames.");
INTEGER_COMMAND_NOID(triggers, getNumberOfTriggers, setNumberOfTriggers, INTEGER_COMMAND_NOID(triggers, getNumberOfTriggers, setNumberOfTriggers,
std::stol, std::stol,
@ -1696,7 +1698,7 @@ class CmdProxy {
"\n\t[Jungfrau][Ctb] Reset FPGA."); "\n\t[Jungfrau][Ctb] Reset FPGA.");
EXECUTE_SET_COMMAND(rebootcontroller, rebootController, EXECUTE_SET_COMMAND(rebootcontroller, rebootController,
"\n\t[Jungfrau][Ctb] Reboot controler (blackfin) of detector."); "\n\t[Jungfrau][Ctb][Gotthard][Mythen3][Gotthard2] Reboot controler (blackfin) of detector.");
EXECUTE_SET_COMMAND(firmwaretest, executeFirmwareTest, EXECUTE_SET_COMMAND(firmwaretest, executeFirmwareTest,
"\n\t[Jungfrau][Gotthard][Mythen3][Gotthard2][Ctb] Firmware test, ie. reads a read fixed pattern from a register."); "\n\t[Jungfrau][Gotthard][Mythen3][Gotthard2][Ctb] Firmware test, ie. reads a read fixed pattern from a register.");

View File

@ -4,7 +4,7 @@
#include "container_utils.h" #include "container_utils.h"
#include "detectorData.h" #include "detectorData.h"
#include "logger.h" #include "logger.h"
#include "multiSlsDetector.h" #include "DetectorImpl.h"
#include "slsDetector.h" #include "slsDetector.h"
#include "sls_detector_defs.h" #include "sls_detector_defs.h"
@ -41,7 +41,7 @@ void freeSharedMemory(int multiId, int detPos) {
using defs = slsDetectorDefs; using defs = slsDetectorDefs;
Detector::Detector(int shm_id) Detector::Detector(int shm_id)
: pimpl(sls::make_unique<multiSlsDetector>(shm_id)) {} : pimpl(sls::make_unique<DetectorImpl>(shm_id)) {}
Detector::~Detector() = default; Detector::~Detector() = default;
@ -51,7 +51,7 @@ void Detector::freeSharedMemory() { pimpl->freeSharedMemory(); }
void Detector::loadConfig(const std::string &fname) { void Detector::loadConfig(const std::string &fname) {
int shm_id = getShmId(); int shm_id = getShmId();
freeSharedMemory(); freeSharedMemory();
pimpl = sls::make_unique<multiSlsDetector>(shm_id); pimpl = sls::make_unique<DetectorImpl>(shm_id);
FILE_LOG(logINFO) << "Loading configuration file: " << fname; FILE_LOG(logINFO) << "Loading configuration file: " << fname;
loadParameters(fname); loadParameters(fname);
} }
@ -148,7 +148,7 @@ Result<defs::detectorSettings> Detector::getSettings(Positions pos) const {
return pimpl->Parallel(&slsDetector::getSettings, pos); return pimpl->Parallel(&slsDetector::getSettings, pos);
} }
void Detector::setSettings(defs::detectorSettings value, Positions pos) { void Detector::setSettings(const defs::detectorSettings value, Positions pos) {
pimpl->Parallel(&slsDetector::setSettings, pos, value); pimpl->Parallel(&slsDetector::setSettings, pos, value);
} }
@ -1652,9 +1652,7 @@ void Detector::setDetectorMode(defs::detectorModeType value, Positions pos) {
// Advanced // Advanced
void Detector::programFPGA(const std::string &fname, Positions pos) { void Detector::programFPGA(const std::string &fname, Positions pos) {
FILE_LOG(logINFO) std::vector<char> buffer = pimpl->readProgrammingFile(fname);
<< "Updating Firmware. This can take awhile. Please be patient...";
std::vector<char> buffer = pimpl->readPofFile(fname);
pimpl->Parallel(&slsDetector::programFPGA, pos, buffer); pimpl->Parallel(&slsDetector::programFPGA, pos, buffer);
} }
@ -1709,6 +1707,14 @@ void Detector::writeAdcRegister(uint32_t addr, uint32_t value, Positions pos) {
pimpl->Parallel(&slsDetector::writeAdcRegister, pos, addr, value); pimpl->Parallel(&slsDetector::writeAdcRegister, pos, addr, value);
} }
bool Detector::getInitialChecks() const {
return pimpl->getInitialChecks();
}
void Detector::setInitialChecks(const bool value) {
pimpl->setInitialChecks(value);
}
// Insignificant // Insignificant
Result<int> Detector::getControlPort(Positions pos) const { Result<int> Detector::getControlPort(Positions pos) const {

View File

@ -1,4 +1,4 @@
#include "multiSlsDetector.h" #include "DetectorImpl.h"
#include "SharedMemory.h" #include "SharedMemory.h"
#include "ZmqSocket.h" #include "ZmqSocket.h"
#include "detectorData.h" #include "detectorData.h"
@ -28,14 +28,14 @@
using namespace sls; using namespace sls;
multiSlsDetector::multiSlsDetector(int multi_id, bool verify, bool update) DetectorImpl::DetectorImpl(int multi_id, bool verify, bool update)
: multiId(multi_id), multi_shm(multi_id, -1) { : multiId(multi_id), multi_shm(multi_id, -1) {
setupMultiDetector(verify, update); setupMultiDetector(verify, update);
} }
multiSlsDetector::~multiSlsDetector() = default; DetectorImpl::~DetectorImpl() = default;
void multiSlsDetector::setupMultiDetector(bool verify, bool update) { void DetectorImpl::setupMultiDetector(bool verify, bool update) {
initSharedMemory(verify); initSharedMemory(verify);
initializeMembers(verify); initializeMembers(verify);
if (update) { if (update) {
@ -43,104 +43,17 @@ void multiSlsDetector::setupMultiDetector(bool verify, bool update) {
} }
} }
template <typename RT, typename... CT> void DetectorImpl::setAcquiringFlag(bool flag) {
std::vector<RT>
multiSlsDetector::serialCall(RT (slsDetector::*somefunc)(CT...),
typename NonDeduced<CT>::type... Args) {
std::vector<RT> result;
result.reserve(detectors.size());
for (auto &d : detectors) {
result.push_back((d.get()->*somefunc)(Args...));
}
return result;
}
template <typename RT, typename... CT>
std::vector<RT>
multiSlsDetector::serialCall(RT (slsDetector::*somefunc)(CT...) const,
typename NonDeduced<CT>::type... Args) const {
std::vector<RT> result;
result.reserve(detectors.size());
for (auto &d : detectors) {
result.push_back((d.get()->*somefunc)(Args...));
}
return result;
}
template <typename RT, typename... CT>
std::vector<RT>
multiSlsDetector::parallelCall(RT (slsDetector::*somefunc)(CT...),
typename NonDeduced<CT>::type... Args) {
std::vector<std::future<RT>> futures;
for (auto &d : detectors) {
futures.push_back(
std::async(std::launch::async, somefunc, d.get(), Args...));
}
std::vector<RT> result;
result.reserve(detectors.size());
for (auto &i : futures) {
result.push_back(i.get());
}
return result;
}
template <typename RT, typename... CT>
std::vector<RT>
multiSlsDetector::parallelCall(RT (slsDetector::*somefunc)(CT...) const,
typename NonDeduced<CT>::type... Args) const {
std::vector<std::future<RT>> futures;
for (auto &d : detectors) {
futures.push_back(
std::async(std::launch::async, somefunc, d.get(), Args...));
}
std::vector<RT> result;
result.reserve(detectors.size());
for (auto &i : futures) {
result.push_back(i.get());
}
return result;
}
template <typename... CT>
void multiSlsDetector::parallelCall(void (slsDetector::*somefunc)(CT...),
typename NonDeduced<CT>::type... Args) {
std::vector<std::future<void>> futures;
for (auto &d : detectors) {
futures.push_back(
std::async(std::launch::async, somefunc, d.get(), Args...));
}
for (auto &i : futures) {
i.get();
}
return;
}
template <typename... CT>
void multiSlsDetector::parallelCall(
void (slsDetector::*somefunc)(CT...) const,
typename NonDeduced<CT>::type... Args) const {
std::vector<std::future<void>> futures;
for (auto &d : detectors) {
futures.push_back(
std::async(std::launch::async, somefunc, d.get(), Args...));
}
for (auto &i : futures) {
i.get();
}
return;
}
void multiSlsDetector::setAcquiringFlag(bool flag) {
multi_shm()->acquiringFlag = flag; multi_shm()->acquiringFlag = flag;
} }
int multiSlsDetector::getMultiId() const { return multiId; } int DetectorImpl::getMultiId() const { return multiId; }
std::string multiSlsDetector::getPackageVersion() const { return GITBRANCH; } std::string DetectorImpl::getPackageVersion() const { return GITBRANCH; }
int64_t multiSlsDetector::getClientSoftwareVersion() const { return APILIB; } int64_t DetectorImpl::getClientSoftwareVersion() const { return APILIB; }
void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { void DetectorImpl::freeSharedMemory(int multiId, int detPos) {
// single // single
if (detPos >= 0) { if (detPos >= 0) {
SharedMemory<sharedSlsDetector> temp_shm(multiId, detPos); SharedMemory<sharedSlsDetector> temp_shm(multiId, detPos);
@ -166,7 +79,7 @@ void multiSlsDetector::freeSharedMemory(int multiId, int detPos) {
} }
} }
void multiSlsDetector::freeSharedMemory() { void DetectorImpl::freeSharedMemory() {
zmqSocket.clear(); zmqSocket.clear();
for (auto &d : detectors) { for (auto &d : detectors) {
d->freeSharedMemory(); d->freeSharedMemory();
@ -178,7 +91,7 @@ void multiSlsDetector::freeSharedMemory() {
client_downstream = false; client_downstream = false;
} }
std::string multiSlsDetector::getUserDetails() { std::string DetectorImpl::getUserDetails() {
if (detectors.empty()) { if (detectors.empty()) {
return std::string("none"); return std::string("none");
} }
@ -212,7 +125,15 @@ std::string multiSlsDetector::getUserDetails() {
return sstream.str(); return sstream.str();
} }
void multiSlsDetector::initSharedMemory(bool verify) { bool DetectorImpl::getInitialChecks() const {
return multi_shm()->initialChecks;
}
void DetectorImpl::setInitialChecks(const bool value) {
multi_shm()->initialChecks = value;
}
void DetectorImpl::initSharedMemory(bool verify) {
if (!multi_shm.IsExisting()) { if (!multi_shm.IsExisting()) {
multi_shm.CreateSharedMemory(); multi_shm.CreateSharedMemory();
initializeDetectorStructure(); initializeDetectorStructure();
@ -230,7 +151,7 @@ void multiSlsDetector::initSharedMemory(bool verify) {
} }
} }
void multiSlsDetector::initializeDetectorStructure() { void DetectorImpl::initializeDetectorStructure() {
multi_shm()->shmversion = MULTI_SHMVERSION; multi_shm()->shmversion = MULTI_SHMVERSION;
multi_shm()->numberOfDetectors = 0; multi_shm()->numberOfDetectors = 0;
multi_shm()->multiDetectorType = GENERIC; multi_shm()->multiDetectorType = GENERIC;
@ -240,10 +161,11 @@ void multiSlsDetector::initializeDetectorStructure() {
multi_shm()->numberOfChannels.y = 0; multi_shm()->numberOfChannels.y = 0;
multi_shm()->acquiringFlag = false; multi_shm()->acquiringFlag = false;
multi_shm()->receiver_upstream = false; multi_shm()->receiver_upstream = false;
multi_shm()->initialChecks = true;
} }
void multiSlsDetector::initializeMembers(bool verify) { void DetectorImpl::initializeMembers(bool verify) {
// multiSlsDetector // DetectorImpl
zmqSocket.clear(); zmqSocket.clear();
// get objects from single det shared memory (open) // get objects from single det shared memory (open)
@ -258,10 +180,10 @@ void multiSlsDetector::initializeMembers(bool verify) {
} }
} }
void multiSlsDetector::updateUserdetails() { void DetectorImpl::updateUserdetails() {
multi_shm()->lastPID = getpid(); multi_shm()->lastPID = getpid();
memset(multi_shm()->lastUser, 0, SHORT_STRING_LENGTH); memset(multi_shm()->lastUser, 0, sizeof(multi_shm()->lastUser));
memset(multi_shm()->lastDate, 0, SHORT_STRING_LENGTH); memset(multi_shm()->lastDate, 0, sizeof(multi_shm()->lastDate));
try { try {
sls::strcpy_safe(multi_shm()->lastUser, exec("whoami").c_str()); sls::strcpy_safe(multi_shm()->lastUser, exec("whoami").c_str());
sls::strcpy_safe(multi_shm()->lastDate, exec("date").c_str()); sls::strcpy_safe(multi_shm()->lastDate, exec("date").c_str());
@ -271,7 +193,7 @@ void multiSlsDetector::updateUserdetails() {
} }
} }
bool multiSlsDetector::isAcquireReady() { bool DetectorImpl::isAcquireReady() {
if (multi_shm()->acquiringFlag) { if (multi_shm()->acquiringFlag) {
FILE_LOG(logWARNING) FILE_LOG(logWARNING)
<< "Acquire has already started. " << "Acquire has already started. "
@ -283,31 +205,26 @@ bool multiSlsDetector::isAcquireReady() {
return true; return true;
} }
std::string multiSlsDetector::exec(const char *cmd) { std::string DetectorImpl::exec(const char *cmd) {
int bufsize = 128; char buffer[128];
char buffer[bufsize]; std::string result;
std::string result = "";
FILE *pipe = popen(cmd, "r"); FILE *pipe = popen(cmd, "r");
if (pipe == nullptr) { if (pipe == nullptr) {
throw RuntimeError("Could not open pipe"); throw RuntimeError("Could not open pipe");
} }
try {
while (feof(pipe) == 0) { while (feof(pipe) == 0) {
if (fgets(buffer, bufsize, pipe) != nullptr) { if (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer; result += buffer;
} }
} }
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe); pclose(pipe);
result.erase(result.find_last_not_of(" \t\n\r") + 1); result.erase(result.find_last_not_of(" \t\n\r") + 1);
return result; return result;
} }
void multiSlsDetector::setVirtualDetectorServers(const int numdet, void DetectorImpl::setVirtualDetectorServers(const int numdet, const int port) {
const int port) {
std::vector<std::string> hostnames; std::vector<std::string> hostnames;
for (int i = 0; i < numdet; ++i) { for (int i = 0; i < numdet; ++i) {
// * 2 is for control and stop port // * 2 is for control and stop port
@ -317,14 +234,16 @@ void multiSlsDetector::setVirtualDetectorServers(const int numdet,
setHostname(hostnames); setHostname(hostnames);
} }
void multiSlsDetector::setHostname(const std::vector<std::string> &name) { void DetectorImpl::setHostname(const std::vector<std::string> &name) {
// this check is there only to allow the previous detsizechan command // this check is there only to allow the previous detsizechan command
if (multi_shm()->numberOfDetectors != 0) { if (multi_shm()->numberOfDetectors != 0) {
FILE_LOG(logWARNING) FILE_LOG(logWARNING)
<< "There are already detector(s) in shared memory." << "There are already detector(s) in shared memory."
"Freeing Shared memory now."; "Freeing Shared memory now.";
bool initialChecks = multi_shm()->initialChecks;
freeSharedMemory(); freeSharedMemory();
setupMultiDetector(); setupMultiDetector();
multi_shm()->initialChecks = initialChecks;
} }
for (const auto &hostname : name) { for (const auto &hostname : name) {
addSlsDetector(hostname); addSlsDetector(hostname);
@ -332,7 +251,7 @@ void multiSlsDetector::setHostname(const std::vector<std::string> &name) {
updateDetectorSize(); updateDetectorSize();
} }
void multiSlsDetector::addSlsDetector(const std::string &hostname) { void DetectorImpl::addSlsDetector(const std::string &hostname) {
FILE_LOG(logINFO) << "Adding detector " << hostname; FILE_LOG(logINFO) << "Adding detector " << hostname;
int port = DEFAULT_PORTNO; int port = DEFAULT_PORTNO;
@ -357,18 +276,20 @@ void multiSlsDetector::addSlsDetector(const std::string &hostname) {
// get type by connecting // get type by connecting
detectorType type = slsDetector::getTypeFromDetector(host, port); detectorType type = slsDetector::getTypeFromDetector(host, port);
int pos = (int)detectors.size(); auto pos = detectors.size();
detectors.push_back( detectors.emplace_back(
sls::make_unique<slsDetector>(type, multiId, pos, false)); sls::make_unique<slsDetector>(type, multiId, pos, false));
multi_shm()->numberOfDetectors = detectors.size(); multi_shm()->numberOfDetectors = detectors.size();
detectors[pos]->setControlPort(port); detectors[pos]->setControlPort(port);
detectors[pos]->setStopPort(port + 1); detectors[pos]->setStopPort(port + 1);
detectors[pos]->setHostname(host); detectors[pos]->setHostname(host, multi_shm()->initialChecks);
// detector type updated by now // detector type updated by now
multi_shm()->multiDetectorType = Parallel(&slsDetector::getDetectorType, {}).tsquash("Inconsistent detector types."); multi_shm()->multiDetectorType =
Parallel(&slsDetector::getDetectorType, {})
.tsquash("Inconsistent detector types.");
} }
void multiSlsDetector::updateDetectorSize() { void DetectorImpl::updateDetectorSize() {
FILE_LOG(logDEBUG) << "Updating Multi-Detector Size: " << size(); FILE_LOG(logDEBUG) << "Updating Multi-Detector Size: " << size();
const slsDetectorDefs::xy det_size = detectors[0]->getNumberOfChannels(); const slsDetectorDefs::xy det_size = detectors[0]->getNumberOfChannels();
@ -403,17 +324,17 @@ void multiSlsDetector::updateDetectorSize() {
} }
} }
int multiSlsDetector::size() const { return detectors.size(); } int DetectorImpl::size() const { return detectors.size(); }
slsDetectorDefs::xy multiSlsDetector::getNumberOfDetectors() const { slsDetectorDefs::xy DetectorImpl::getNumberOfDetectors() const {
return multi_shm()->numberOfDetector; return multi_shm()->numberOfDetector;
} }
slsDetectorDefs::xy multiSlsDetector::getNumberOfChannels() const { slsDetectorDefs::xy DetectorImpl::getNumberOfChannels() const {
return multi_shm()->numberOfChannels; return multi_shm()->numberOfChannels;
} }
void multiSlsDetector::setNumberOfChannels(const slsDetectorDefs::xy c) { void DetectorImpl::setNumberOfChannels(const slsDetectorDefs::xy c) {
if (size() > 1) { if (size() > 1) {
throw RuntimeError( throw RuntimeError(
"Set the number of channels before setting hostname."); "Set the number of channels before setting hostname.");
@ -421,7 +342,7 @@ void multiSlsDetector::setNumberOfChannels(const slsDetectorDefs::xy c) {
multi_shm()->numberOfChannels = c; multi_shm()->numberOfChannels = c;
} }
void multiSlsDetector::setGapPixelsinReceiver(bool enable) { void DetectorImpl::setGapPixelsinReceiver(bool enable) {
Parallel(&slsDetector::enableGapPixels, {}, static_cast<int>(enable)); Parallel(&slsDetector::enableGapPixels, {}, static_cast<int>(enable));
// update number of channels // update number of channels
Result<slsDetectorDefs::xy> res = Result<slsDetectorDefs::xy> res =
@ -434,7 +355,7 @@ void multiSlsDetector::setGapPixelsinReceiver(bool enable) {
} }
} }
int multiSlsDetector::createReceivingDataSockets(const bool destroy) { int DetectorImpl::createReceivingDataSockets(const bool destroy) {
if (destroy) { if (destroy) {
FILE_LOG(logINFO) << "Going to destroy data sockets"; FILE_LOG(logINFO) << "Going to destroy data sockets";
// close socket // close socket
@ -452,7 +373,8 @@ int multiSlsDetector::createReceivingDataSockets(const bool destroy) {
if (multi_shm()->multiDetectorType == EIGER) { if (multi_shm()->multiDetectorType == EIGER) {
numSocketsPerDetector = 2; numSocketsPerDetector = 2;
} }
if (Parallel(&slsDetector::getNumberofUDPInterfacesFromShm, {}).squash() == 2) { if (Parallel(&slsDetector::getNumberofUDPInterfacesFromShm, {}).squash() ==
2) {
numSocketsPerDetector = 2; numSocketsPerDetector = 2;
} }
numSockets *= numSocketsPerDetector; numSockets *= numSocketsPerDetector;
@ -464,7 +386,8 @@ int multiSlsDetector::createReceivingDataSockets(const bool destroy) {
try { try {
zmqSocket.push_back(sls::make_unique<ZmqSocket>( zmqSocket.push_back(sls::make_unique<ZmqSocket>(
detectors[iSocket / numSocketsPerDetector] detectors[iSocket / numSocketsPerDetector]
->getClientStreamingIP().str() ->getClientStreamingIP()
.str()
.c_str(), .c_str(),
portnum)); portnum));
FILE_LOG(logINFO) << "Zmq Client[" << iSocket << "] at " FILE_LOG(logINFO) << "Zmq Client[" << iSocket << "] at "
@ -482,7 +405,7 @@ int multiSlsDetector::createReceivingDataSockets(const bool destroy) {
return OK; return OK;
} }
void multiSlsDetector::readFrameFromReceiver() { void DetectorImpl::readFrameFromReceiver() {
int nX = 0; int nX = 0;
int nY = 0; int nY = 0;
@ -491,7 +414,9 @@ void multiSlsDetector::readFrameFromReceiver() {
bool gappixelsenable = false; bool gappixelsenable = false;
bool quadEnable = false; bool quadEnable = false;
bool eiger = false; bool eiger = false;
bool numInterfaces = Parallel(&slsDetector::getNumberofUDPInterfacesFromShm, {}).squash(); // cannot pick up from zmq bool numInterfaces =
Parallel(&slsDetector::getNumberofUDPInterfacesFromShm, {})
.squash(); // cannot pick up from zmq
bool runningList[zmqSocket.size()], connectList[zmqSocket.size()]; bool runningList[zmqSocket.size()], connectList[zmqSocket.size()];
int numRunning = 0; int numRunning = 0;
@ -518,7 +443,7 @@ void multiSlsDetector::readFrameFromReceiver() {
uint32_t size = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0; uint32_t size = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0;
float bytesPerPixel = 0; float bytesPerPixel = 0;
// header info every header // header info every header
std::string currentFileName = ""; std::string currentFileName;
uint64_t currentAcquisitionIndex = -1, currentFrameIndex = -1, uint64_t currentAcquisitionIndex = -1, currentFrameIndex = -1,
currentFileIndex = -1; currentFileIndex = -1;
uint32_t currentSubFrameIndex = -1, coordX = -1, coordY = -1, uint32_t currentSubFrameIndex = -1, coordX = -1, coordY = -1,
@ -651,19 +576,19 @@ void multiSlsDetector::readFrameFromReceiver() {
if (eiger && (flippedDataX != 0U)) { if (eiger && (flippedDataX != 0U)) {
for (uint32_t i = 0; i < nPixelsY; ++i) { for (uint32_t i = 0; i < nPixelsY; ++i) {
memcpy(((char *)multiframe) + memcpy((multiframe) +
((yoffset + (nPixelsY - 1 - i)) * ((yoffset + (nPixelsY - 1 - i)) *
rowoffset) + rowoffset) +
xoffset, xoffset,
(char *)image + (i * singledetrowoffset), image + (i * singledetrowoffset),
singledetrowoffset); singledetrowoffset);
} }
} else { } else {
for (uint32_t i = 0; i < nPixelsY; ++i) { for (uint32_t i = 0; i < nPixelsY; ++i) {
std::cout << i << " " << std::endl;
memcpy(((char *)multiframe) + memcpy((multiframe) + ((yoffset + i) * rowoffset) +
((yoffset + i) * rowoffset) + xoffset, xoffset,
(char *)image + (i * singledetrowoffset), image + (i * singledetrowoffset),
singledetrowoffset); singledetrowoffset);
} }
} }
@ -695,19 +620,20 @@ void multiSlsDetector::readFrameFromReceiver() {
<< "\n\t nDetPixelsX: " << nDetPixelsX << "\n\t nDetPixelsX: " << nDetPixelsX
<< "\n\t nDetPixelsY: " << nDetPixelsY << "\n\t nDetPixelsY: " << nDetPixelsY
<< "\n\t databytes: " << n; << "\n\t databytes: " << n;
thisData = new detectorData( thisData =
getCurrentProgress(), currentFileName.c_str(), nDetPixelsX, new detectorData(getCurrentProgress(), currentFileName,
nDetPixelsY, multigappixels, n, dynamicRange, nDetPixelsX, nDetPixelsY, multigappixels,
currentFileIndex); n, dynamicRange, currentFileIndex);
} }
// normal pixels // normal pixels
else { else {
thisData = new detectorData( thisData =
getCurrentProgress(), currentFileName.c_str(), nDetPixelsX, new detectorData(getCurrentProgress(), currentFileName,
nDetPixelsY, multiframe, multisize, dynamicRange, nDetPixelsX, nDetPixelsY, multiframe,
currentFileIndex); multisize, dynamicRange, currentFileIndex);
} }
dataReady(thisData, currentFrameIndex, dataReady(
thisData, currentFrameIndex,
((dynamicRange == 32 && eiger) ? currentSubFrameIndex : -1), ((dynamicRange == 32 && eiger) ? currentSubFrameIndex : -1),
pCallbackArg); pCallbackArg);
delete thisData; delete thisData;
@ -750,7 +676,7 @@ void multiSlsDetector::readFrameFromReceiver() {
delete[] multigappixels; delete[] multigappixels;
} }
int multiSlsDetector::processImageWithGapPixels(char *image, char *&gpImage, int DetectorImpl::processImageWithGapPixels(char *image, char *&gpImage,
bool quadEnable) { bool quadEnable) {
// eiger 4 bit mode // eiger 4 bit mode
int nxb = int nxb =
@ -885,7 +811,7 @@ int multiSlsDetector::processImageWithGapPixels(char *image, char *&gpImage,
return gapdatabytes; return gapdatabytes;
} }
bool multiSlsDetector::enableDataStreamingToClient(int enable) { bool DetectorImpl::enableDataStreamingToClient(int enable) {
if (enable >= 0) { if (enable >= 0) {
// destroy data threads // destroy data threads
if (enable == 0) { if (enable == 0) {
@ -900,8 +826,7 @@ bool multiSlsDetector::enableDataStreamingToClient(int enable) {
return client_downstream; return client_downstream;
} }
void DetectorImpl::savePattern(const std::string &fname) {
void multiSlsDetector::savePattern(const std::string &fname) {
// std::ofstream outfile; // std::ofstream outfile;
// outfile.open(fname.c_str(), std::ios_base::out); // outfile.open(fname.c_str(), std::ios_base::out);
// if (!outfile.is_open()) { // if (!outfile.is_open()) {
@ -941,31 +866,23 @@ void multiSlsDetector::savePattern(const std::string &fname) {
// multiSlsDetectorClient(cmd, GET_ACTION, this, outfile); // multiSlsDetectorClient(cmd, GET_ACTION, this, outfile);
} }
void DetectorImpl::registerAcquisitionFinishedCallback(void (*func)(double, int,
void *),
void multiSlsDetector::registerAcquisitionFinishedCallback( void *pArg) {
void (*func)(double, int, void *), void *pArg) {
acquisition_finished = func; acquisition_finished = func;
acqFinished_p = pArg; acqFinished_p = pArg;
} }
void multiSlsDetector::registerDataCallback( void DetectorImpl::registerDataCallback(void (*userCallback)(detectorData *,
void (*userCallback)(detectorData *, uint64_t, uint32_t, void *), uint64_t, uint32_t,
void *),
void *pArg) { void *pArg) {
dataReady = userCallback; dataReady = userCallback;
pCallbackArg = pArg; pCallbackArg = pArg;
if (Parallel(&slsDetector::getUseReceiverFlag, {}).squash(false)) { enableDataStreamingToClient(dataReady == nullptr ? 0 : 1);
if (dataReady == nullptr) {
enableDataStreamingToClient(0);
Parallel(&slsDetector::enableDataStreamingFromReceiver, {}, 0);
} else {
enableDataStreamingToClient(1);
Parallel(&slsDetector::enableDataStreamingFromReceiver, {}, 1);
}
}
} }
double multiSlsDetector::setTotalProgress() { double DetectorImpl::setTotalProgress() {
int64_t nf = Parallel(&slsDetector::getNumberOfFramesFromShm, {}) int64_t nf = Parallel(&slsDetector::getNumberOfFramesFromShm, {})
.tsquash("Inconsistent number of frames"); .tsquash("Inconsistent number of frames");
int64_t nc = Parallel(&slsDetector::getNumberOfTriggersFromShm, {}) int64_t nc = Parallel(&slsDetector::getNumberOfTriggersFromShm, {})
@ -976,7 +893,8 @@ double multiSlsDetector::setTotalProgress() {
int ns = 1; int ns = 1;
if (multi_shm()->multiDetectorType == JUNGFRAU) { if (multi_shm()->multiDetectorType == JUNGFRAU) {
ns = Parallel(&slsDetector::getNumberOfAdditionalStorageCellsFromShm, {}) ns =
Parallel(&slsDetector::getNumberOfAdditionalStorageCellsFromShm, {})
.tsquash("Inconsistent number of additional storage cells"); .tsquash("Inconsistent number of additional storage cells");
++ns; ++ns;
} }
@ -987,30 +905,28 @@ double multiSlsDetector::setTotalProgress() {
return totalProgress; return totalProgress;
} }
double multiSlsDetector::getCurrentProgress() { double DetectorImpl::getCurrentProgress() {
std::lock_guard<std::mutex> lock(mp); std::lock_guard<std::mutex> lock(mp);
return 100. * progressIndex / totalProgress; return 100. * progressIndex / totalProgress;
} }
void multiSlsDetector::incrementProgress() { void DetectorImpl::incrementProgress() {
std::lock_guard<std::mutex> lock(mp); std::lock_guard<std::mutex> lock(mp);
progressIndex += 1; progressIndex += 1;
std::cout << std::fixed << std::setprecision(2) << std::setw(6) std::cout << std::fixed << std::setprecision(2) << std::setw(6)
<< 100. * progressIndex / totalProgress << 100. * progressIndex / totalProgress << " \%";
<< " \%";
std::cout << '\r' << std::flush; std::cout << '\r' << std::flush;
} }
void multiSlsDetector::setCurrentProgress(int64_t i) { void DetectorImpl::setCurrentProgress(int64_t i) {
std::lock_guard<std::mutex> lock(mp); std::lock_guard<std::mutex> lock(mp);
progressIndex = (double)i; progressIndex = (double)i;
std::cout << std::fixed << std::setprecision(2) << std::setw(6) std::cout << std::fixed << std::setprecision(2) << std::setw(6)
<< 100. * progressIndex / totalProgress << 100. * progressIndex / totalProgress << " \%";
<< " \%";
std::cout << '\r' << std::flush; std::cout << '\r' << std::flush;
} }
int multiSlsDetector::acquire() { int DetectorImpl::acquire() {
// ensure acquire isnt started multiple times by same client // ensure acquire isnt started multiple times by same client
if (!isAcquireReady()) { if (!isAcquireReady()) {
return FAIL; return FAIL;
@ -1020,21 +936,23 @@ int multiSlsDetector::acquire() {
struct timespec begin, end; struct timespec begin, end;
clock_gettime(CLOCK_REALTIME, &begin); clock_gettime(CLOCK_REALTIME, &begin);
// in the real time acquisition loop, processing thread will wait for a post // in the real time acquisition loop, processing thread will wait for a
// each time // post each time
sem_init(&sem_newRTAcquisition, 1, 0); sem_init(&sem_newRTAcquisition, 1, 0);
// in the real time acquistion loop, main thread will wait for processing // in the real time acquistion loop, main thread will wait for
// thread to be done each time (which in turn waits for receiver/ext // processing thread to be done each time (which in turn waits for
// process) // receiver/ext process)
sem_init(&sem_endRTAcquisition, 1, 0); sem_init(&sem_endRTAcquisition, 1, 0);
bool receiver = Parallel(&slsDetector::getUseReceiverFlag, {}).squash(false); bool receiver =
Parallel(&slsDetector::getUseReceiverFlag, {}).squash(false);
progressIndex = 0; progressIndex = 0;
setJoinThreadFlag(false); setJoinThreadFlag(false);
// verify receiver is idle // verify receiver is idle
if (receiver) { if (receiver) {
if (Parallel(&slsDetector::getReceiverStatus, {}).squash(ERROR) != IDLE) { if (Parallel(&slsDetector::getReceiverStatus, {}).squash(ERROR) !=
IDLE) {
Parallel(&slsDetector::stopReceiver, {}); Parallel(&slsDetector::stopReceiver, {});
} }
} }
@ -1083,8 +1001,7 @@ int multiSlsDetector::acquire() {
auto t = Parallel(&slsDetector::getRunStatus, {}); auto t = Parallel(&slsDetector::getRunStatus, {});
if (t.equal()) if (t.equal())
status = t.front(); status = t.front();
acquisition_finished(getCurrentProgress(), status, acquisition_finished(getCurrentProgress(), status, acqFinished_p);
acqFinished_p);
} }
sem_destroy(&sem_newRTAcquisition); sem_destroy(&sem_newRTAcquisition);
@ -1103,12 +1020,12 @@ int multiSlsDetector::acquire() {
return OK; return OK;
} }
void multiSlsDetector::startProcessingThread() { void DetectorImpl::startProcessingThread() {
setTotalProgress(); setTotalProgress();
dataProcessingThread = std::thread(&multiSlsDetector::processData, this); dataProcessingThread = std::thread(&DetectorImpl::processData, this);
} }
void multiSlsDetector::processData() { void DetectorImpl::processData() {
if (Parallel(&slsDetector::getUseReceiverFlag, {}).squash(false)) { if (Parallel(&slsDetector::getUseReceiverFlag, {}).squash(false)) {
if (dataReady != nullptr) { if (dataReady != nullptr) {
readFrameFromReceiver(); readFrameFromReceiver();
@ -1126,7 +1043,8 @@ void multiSlsDetector::processData() {
} }
} }
// get progress // get progress
caught = Parallel(&slsDetector::getFramesCaughtByReceiver, {0}).squash(); caught = Parallel(&slsDetector::getFramesCaughtByReceiver, {0})
.squash();
// updating progress // updating progress
if (caught != -1) { if (caught != -1) {
@ -1143,17 +1061,17 @@ void multiSlsDetector::processData() {
} }
} }
bool multiSlsDetector::getJoinThreadFlag() const { bool DetectorImpl::getJoinThreadFlag() const {
std::lock_guard<std::mutex> lock(mp); std::lock_guard<std::mutex> lock(mp);
return jointhread; return jointhread;
} }
void multiSlsDetector::setJoinThreadFlag(bool value) { void DetectorImpl::setJoinThreadFlag(bool value) {
std::lock_guard<std::mutex> lock(mp); std::lock_guard<std::mutex> lock(mp);
jointhread = value; jointhread = value;
} }
int multiSlsDetector::kbhit() { int DetectorImpl::kbhit() {
struct timeval tv; struct timeval tv;
fd_set fds; fd_set fds;
tv.tv_sec = 0; tv.tv_sec = 0;
@ -1164,11 +1082,33 @@ int multiSlsDetector::kbhit() {
return FD_ISSET(STDIN_FILENO, &fds); return FD_ISSET(STDIN_FILENO, &fds);
} }
std::vector<char> multiSlsDetector::readPofFile(const std::string &fname) { std::vector<char> DetectorImpl::readProgrammingFile(const std::string &fname) {
// validate type of file
bool isPof = false;
switch (multi_shm()->multiDetectorType) {
case JUNGFRAU:
case CHIPTESTBOARD:
if (fname.find(".pof") == std::string::npos) {
throw RuntimeError("Programming file must be a pof file.");
}
isPof = true;
break;
case MYTHEN3:
case GOTTHARD2:
if (fname.find(".rbf") == std::string::npos) {
throw RuntimeError("Programming file must be an rbf file.");
}
break;
default:
throw RuntimeError("Not implemented for this detector");
}
FILE_LOG(logINFO)
<< "Updating Firmware. This can take awhile. Please be patient...";
FILE_LOG(logDEBUG1) << "Programming FPGA with file name:" << fname; FILE_LOG(logDEBUG1) << "Programming FPGA with file name:" << fname;
size_t filesize = 0; size_t filesize = 0;
// check if it exists // check if it exists
struct stat st; struct stat st;
if (stat(fname.c_str(), &st) != 0) { if (stat(fname.c_str(), &st) != 0) {
throw RuntimeError("Program FPGA: Programming file does not exist"); throw RuntimeError("Program FPGA: Programming file does not exist");
@ -1196,32 +1136,43 @@ std::vector<char> multiSlsDetector::readPofFile(const std::string &fname) {
// convert src to dst rawbin // convert src to dst rawbin
FILE_LOG(logDEBUG1) << "Converting " << fname << " to " << destfname; FILE_LOG(logDEBUG1) << "Converting " << fname << " to " << destfname;
{ {
int filepos, x, y, i; constexpr int pofNumHeaderBytes = 0x11C;
// Remove header (0...11C) constexpr int pofFooterOfst = 0x1000000;
for (filepos = 0; filepos < 0x11C; ++filepos) { int dstFilePos = 0;
if (isPof) {
// Read header and discard
for (int i = 0; i < pofNumHeaderBytes; ++i) {
fgetc(src); fgetc(src);
} }
// Write 0x80 times 0xFF (0...7F) // Write 0xFF to destination 0x80 times (padding)
{ constexpr int pofNumPadding{0x80};
char c = 0xFF; constexpr uint8_t c{0xFF};
for (filepos = 0; filepos < 0x80; ++filepos) { while (dstFilePos < pofNumPadding) {
write(dst, &c, 1); write(dst, &c, sizeof(c));
++dstFilePos;
} }
} }
// Swap bits and write to file // Swap bits from source and write to dest
for (filepos = 0x80; filepos < 0x1000000; ++filepos) { while (!feof(src)) {
x = fgetc(src); // pof: exit early to discard footer
if (x < 0) { if (isPof && dstFilePos >= pofFooterOfst) {
break; break;
} }
y = 0; // read source
for (i = 0; i < 8; ++i) { int s = fgetc(src);
y = y | if (s < 0) {
(((x & (1 << i)) >> i) << (7 - i)); // This swaps the bits break;
} }
write(dst, &y, 1); // swap bits
int d = 0;
for (int i = 0; i < 8; ++i) {
d = d | (((s & (1 << i)) >> i) << (7 - i));
} }
if (filepos < 0x1000000) { write(dst, &d, 1);
++dstFilePos;
}
// validate pof: read less than footer offset
if (isPof && dstFilePos < pofFooterOfst) {
throw RuntimeError( throw RuntimeError(
"Could not convert programming file. EOF before end of flash"); "Could not convert programming file. EOF before end of flash");
} }

View File

@ -17,9 +17,8 @@ class detectorData;
#include <vector> #include <vector>
#define MULTI_SHMAPIVERSION 0x190809 #define MULTI_SHMAPIVERSION 0x190809
#define MULTI_SHMVERSION 0x190819 #define MULTI_SHMVERSION 0x200131
#define SHORT_STRING_LENGTH 50 #define SHORT_STRING_LENGTH 50
#define DATE_LENGTH 30
#include <future> #include <future>
#include <numeric> #include <numeric>
@ -64,9 +63,12 @@ struct sharedMultiSlsDetector {
/** data streaming (up stream) enable in receiver */ /** data streaming (up stream) enable in receiver */
bool receiver_upstream; bool receiver_upstream;
/** initial checks */
bool initialChecks;
}; };
class multiSlsDetector : public virtual slsDetectorDefs { class DetectorImpl : public virtual slsDetectorDefs {
public: public:
/** /**
* Constructor * Constructor
@ -75,13 +77,13 @@ class multiSlsDetector : public virtual slsDetectorDefs {
* one * one
* @param update true to update last user pid, date etc * @param update true to update last user pid, date etc
*/ */
explicit multiSlsDetector(int multi_id = 0, bool verify = true, explicit DetectorImpl(int multi_id = 0, bool verify = true,
bool update = true); bool update = true);
/** /**
* Destructor * Destructor
*/ */
virtual ~multiSlsDetector(); virtual ~DetectorImpl();
template <class CT> struct NonDeduced { using type = CT; }; template <class CT> struct NonDeduced { using type = CT; };
template <typename RT, typename... CT> template <typename RT, typename... CT>
@ -190,44 +192,6 @@ class multiSlsDetector : public virtual slsDetectorDefs {
} }
} }
/**
* Loop through the detectors serially and return the result as a vector
*/
template <typename RT, typename... CT>
std::vector<RT> serialCall(RT (slsDetector::*somefunc)(CT...),
typename NonDeduced<CT>::type... Args);
/**
* Loop through the detectors serially and return the result as a vector
* Const qualified version
*/
template <typename RT, typename... CT>
std::vector<RT> serialCall(RT (slsDetector::*somefunc)(CT...) const,
typename NonDeduced<CT>::type... Args) const;
/**
* Loop through the detectors in parallel and return the result as a vector
*/
template <typename RT, typename... CT>
std::vector<RT> parallelCall(RT (slsDetector::*somefunc)(CT...),
typename NonDeduced<CT>::type... Args);
/**
* Loop through the detectors in parallel and return the result as a vector
* Const qualified version
*/
template <typename RT, typename... CT>
std::vector<RT> parallelCall(RT (slsDetector::*somefunc)(CT...) const,
typename NonDeduced<CT>::type... Args) const;
template <typename... CT>
void parallelCall(void (slsDetector::*somefunc)(CT...),
typename NonDeduced<CT>::type... Args);
template <typename... CT>
void parallelCall(void (slsDetector::*somefunc)(CT...) const,
typename NonDeduced<CT>::type... Args) const;
/** set acquiring flag in shared memory */ /** set acquiring flag in shared memory */
void setAcquiringFlag(bool flag); void setAcquiringFlag(bool flag);
@ -248,6 +212,12 @@ class multiSlsDetector : public virtual slsDetectorDefs {
/** Get user details of shared memory */ /** Get user details of shared memory */
std::string getUserDetails(); std::string getUserDetails();
bool getInitialChecks() const;
/** initial compaibility and other server start up checks
* default enabled */
void setInitialChecks(const bool value);
/** /**
* Connect to Virtual Detector Servers at local host * Connect to Virtual Detector Servers at local host
* @param ndet number of detectors * @param ndet number of detectors
@ -323,11 +293,13 @@ class multiSlsDetector : public virtual slsDetectorDefs {
/** /**
* Convert raw file * Convert raw file
* @param fname name of pof file * [Jungfrau][Ctb] from pof file
* @param fpgasrc pointer in memory to read pof to * [Mythen3][Gotthard2] from rbf file
* @param fname name of pof/rbf file
* @param fpgasrc pointer in memory to read programming file to
* @returns file size * @returns file size
*/ */
std::vector<char> readPofFile(const std::string &fname); std::vector<char> readProgrammingFile(const std::string &fname);
private: private:
/** /**

View File

@ -279,13 +279,21 @@ void slsDetector::freeSharedMemory() {
} }
} }
void slsDetector::setHostname(const std::string &hostname) { void slsDetector::setHostname(const std::string &hostname, const bool initialChecks) {
sls::strcpy_safe(shm()->hostname, hostname.c_str()); sls::strcpy_safe(shm()->hostname, hostname.c_str());
auto client = DetectorSocket(shm()->hostname, shm()->controlPort); auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.close(); client.close();
FILE_LOG(logINFO) << "Checking Detector Version Compatibility"; FILE_LOG(logINFO) << "Checking Detector Version Compatibility";
if (!initialChecks) {
try {
checkDetectorVersionCompatibility(); checkDetectorVersionCompatibility();
} catch (const DetectorError& e) {
FILE_LOG(logWARNING) << "Bypassing Initial Checks at your own risk!";
}
} else {
checkDetectorVersionCompatibility();
}
FILE_LOG(logINFO) << "Detector connecting - updating!"; FILE_LOG(logINFO) << "Detector connecting - updating!";
updateCachedDetectorVariables(); updateCachedDetectorVariables();
@ -1156,7 +1164,7 @@ void slsDetector::stopAcquisition() {
void slsDetector::sendSoftwareTrigger() { void slsDetector::sendSoftwareTrigger() {
FILE_LOG(logDEBUG1) << "Sending software trigger"; FILE_LOG(logDEBUG1) << "Sending software trigger";
sendToDetector(F_SOFTWARE_TRIGGER); sendToDetectorStop(F_SOFTWARE_TRIGGER);
FILE_LOG(logDEBUG1) << "Sending software trigger successful"; FILE_LOG(logDEBUG1) << "Sending software trigger successful";
} }
@ -1518,8 +1526,8 @@ int slsDetector::setDynamicRange(int n) {
// update speed for usability // update speed for usability
if (dr == 32) { if (dr == 32) {
FILE_LOG(logINFO) << "Setting Clock to Quarter Speed to cope with Dynamic Range of 32"; setClockDivider(RUN_CLOCK, 2); FILE_LOG(logINFO) << "Setting Clock to Quarter Speed to cope with Dynamic Range of 32"; setClockDivider(RUN_CLOCK, 2);
} else if (dr == 16) { } else {
FILE_LOG(logINFO) << "Setting Clock to Half Speed to cope with Dynamic Range of 16"; setClockDivider(RUN_CLOCK, 1); FILE_LOG(logINFO) << "Setting Clock to Full Speed to cope with Dynamic Range of " << dr; setClockDivider(RUN_CLOCK, 0);
} }
} }
@ -2888,23 +2896,28 @@ int slsDetector::setStoragecellStart(int pos) {
} }
void slsDetector::programFPGA(std::vector<char> buffer) { void slsDetector::programFPGA(std::vector<char> buffer) {
// validate type
switch (shm()->myDetectorType) { switch (shm()->myDetectorType) {
case JUNGFRAU: case JUNGFRAU:
case CHIPTESTBOARD: case CHIPTESTBOARD:
case MOENCH: programFPGAviaBlackfin(buffer);
break;
case MYTHEN3:
case GOTTHARD2:
programFPGAviaNios(buffer);
break; break;
default: default:
throw RuntimeError("Program FPGA is not implemented for this detector"); throw RuntimeError("Program FPGA is not implemented for this detector");
} }
}
size_t filesize = buffer.size(); void slsDetector::programFPGAviaBlackfin(std::vector<char> buffer) {
uint64_t filesize = buffer.size();
// send program from memory to detector // send program from memory to detector
int fnum = F_PROGRAM_FPGA; int fnum = F_PROGRAM_FPGA;
int ret = FAIL; int ret = FAIL;
char mess[MAX_STR_LENGTH] = {0}; char mess[MAX_STR_LENGTH] = {0};
FILE_LOG(logINFO) << "Sending programming binary to detector " << detId FILE_LOG(logINFO) << "Sending programming binary (from pof) to detector " << detId
<< " (" << shm()->hostname << ")"; << " (" << shm()->hostname << ")";
auto client = DetectorSocket(shm()->hostname, shm()->controlPort); auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
@ -2921,7 +2934,6 @@ void slsDetector::programFPGA(std::vector<char> buffer) {
} }
// erasing flash // erasing flash
if (ret != FAIL) {
FILE_LOG(logINFO) << "Erasing Flash for detector " << detId << " (" FILE_LOG(logINFO) << "Erasing Flash for detector " << detId << " ("
<< shm()->hostname << ")"; << shm()->hostname << ")";
printf("%d%%\r", 0); printf("%d%%\r", 0);
@ -2944,12 +2956,12 @@ void slsDetector::programFPGA(std::vector<char> buffer) {
<< shm()->hostname << ")"; << shm()->hostname << ")";
printf("%d%%\r", 0); printf("%d%%\r", 0);
std::cout << std::flush; std::cout << std::flush;
}
// sending program in parts of 2mb each // sending program in parts of 2mb each
size_t unitprogramsize = 0; uint64_t unitprogramsize = 0;
int currentPointer = 0; int currentPointer = 0;
size_t totalsize = filesize; uint64_t totalsize = filesize;
while (filesize > 0) { while (filesize > 0) {
unitprogramsize = MAX_FPGAPROGRAMSIZE; // 2mb unitprogramsize = MAX_FPGAPROGRAMSIZE; // 2mb
if (unitprogramsize > filesize) { // less than 2mb if (unitprogramsize > filesize) { // less than 2mb
@ -2967,7 +2979,7 @@ void slsDetector::programFPGA(std::vector<char> buffer) {
os << "Detector " << detId << " (" << shm()->hostname << ")" os << "Detector " << detId << " (" << shm()->hostname << ")"
<< " returned error: " << mess; << " returned error: " << mess;
throw RuntimeError(os.str()); throw RuntimeError(os.str());
} else { }
filesize -= unitprogramsize; filesize -= unitprogramsize;
currentPointer += unitprogramsize; currentPointer += unitprogramsize;
@ -2978,8 +2990,42 @@ void slsDetector::programFPGA(std::vector<char> buffer) {
100)); 100));
std::cout << std::flush; std::cout << std::flush;
} }
}
printf("\n"); printf("\n");
FILE_LOG(logINFO) << "FPGA programmed successfully";
rebootController();
}
void slsDetector::programFPGAviaNios(std::vector<char> buffer) {
uint64_t filesize = buffer.size();
int fnum = F_PROGRAM_FPGA;
int ret = FAIL;
char mess[MAX_STR_LENGTH] = {0};
FILE_LOG(logINFO) << "Sending programming binary (from rbf) to detector " << detId
<< " (" << shm()->hostname << ")";
auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.Send(&fnum, sizeof(fnum));
// filesize
client.Send(&filesize, sizeof(filesize));
client.Receive(&ret, sizeof(ret));
if (ret == FAIL) {
client.Receive(mess, sizeof(mess));
std::ostringstream os;
os << "Detector " << detId << " (" << shm()->hostname << ")"
<< " returned error: " << mess;
throw RuntimeError(os.str());
}
// program
client.Send(&buffer[0], filesize);
client.Receive(&ret, sizeof(ret));
if (ret == FAIL) {
client.Receive(mess, sizeof(mess));
std::ostringstream os;
os << "Detector " << detId << " (" << shm()->hostname << ")"
<< " returned error: " << mess;
throw RuntimeError(os.str());
}
FILE_LOG(logINFO) << "FPGA programmed successfully";
rebootController(); rebootController();
} }
@ -2999,15 +3045,9 @@ void slsDetector::copyDetectorServer(const std::string &fname,
} }
void slsDetector::rebootController() { void slsDetector::rebootController() {
if (shm()->myDetectorType == EIGER) { FILE_LOG(logDEBUG1) << "Rebooting Controller";
throw RuntimeError( sendToDetector(F_REBOOT_CONTROLLER, nullptr, nullptr);
"Reboot controller not implemented for this detector"); FILE_LOG(logINFO) << "Controller rebooted successfully!";
}
int fnum = F_REBOOT_CONTROLLER;
FILE_LOG(logINFO) << "Sending reboot controller to detector " << detId
<< " (" << shm()->hostname << ")";
auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.Send(&fnum, sizeof(fnum));
} }
int slsDetector::powerChip(int ival) { int slsDetector::powerChip(int ival) {

View File

@ -252,8 +252,11 @@ class slsDetector : public virtual slsDetectorDefs {
/** /**
* Sets the hostname, if online flag is set connects to update the detector * Sets the hostname, if online flag is set connects to update the detector
* @param name hostname * @param name hostname
* @param initialChecks enable or disable initial compatibility checks
* and other server start up checks. Enabled by default. Disable only
* for advanced users!
*/ */
void setHostname(const std::string &hostname); void setHostname(const std::string &hostname, const bool initialChecks);
/** /**
* Gets the hostname of detector * Gets the hostname of detector
@ -1382,11 +1385,17 @@ class slsDetector : public virtual slsDetectorDefs {
int setStoragecellStart(int pos = -1); int setStoragecellStart(int pos = -1);
/** /**
* Programs FPGA with pof file (Jungfrau, CTB, Moench) * [Jungfau][Ctb] Programs FPGA with raw file from pof file
* [Mythen3][Gotthard2] Programs FPGA with raw file from rbf file
* @param buffer programming file in memory * @param buffer programming file in memory
*/ */
void programFPGA(std::vector<char> buffer); void programFPGA(std::vector<char> buffer);
/** [Jungfau][Ctb] */
void programFPGAviaBlackfin(std::vector<char> buffer);
/** [Mythen3][Gotthard2] */
void programFPGAviaNios(std::vector<char> buffer);
/** /**
* Resets FPGA (Jungfrau) * Resets FPGA (Jungfrau)
*/ */
@ -1401,6 +1410,7 @@ class slsDetector : public virtual slsDetectorDefs {
const std::string &hostname); const std::string &hostname);
/** /**
* [Jungfrau][Ctb][Gotthard][Mythen3][Gotthard2]
* Reboot detector controller (blackfin/ powerpc) * Reboot detector controller (blackfin/ powerpc)
*/ */
void rebootController(); void rebootController();

View File

@ -6,6 +6,7 @@ target_sources(tests PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-eiger.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-eiger.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-jungfrau.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-jungfrau.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-mythen3.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-mythen3.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-gotthard2.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-global.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-global.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-Result.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test-Result.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdParser.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test-CmdParser.cpp

View File

@ -333,6 +333,7 @@ TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
det.setDAC(defs::VCP, vcp[i], false, {i}); det.setDAC(defs::VCP, vcp[i], false, {i});
} }
} }
// gotthard
REQUIRE_THROWS(proxy.Call("vref_ds", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vref_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascn_pb", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vcascn_pb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascp_pb", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vcascp_pb", {}, -1, GET));
@ -341,6 +342,7 @@ TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
REQUIRE_THROWS(proxy.Call("vin_cm", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vin_cm", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_comp", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vref_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("ib_test_c", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("ib_test_c", {}, -1, GET));
// mythen3
REQUIRE_THROWS(proxy.Call("vpreamp", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vpreamp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vshaper", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vshaper", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vshaperneg", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vshaperneg", {}, -1, GET));
@ -357,6 +359,7 @@ TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
REQUIRE_THROWS(proxy.Call("vcas", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vcas", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vicin", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vicin", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vipre_out", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vipre_out", {}, -1, GET));
// gotthard2
REQUIRE_THROWS(proxy.Call("vref_h_adc", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vref_h_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp_fe", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vb_comp_fe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp_adc", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vb_comp_adc", {}, -1, GET));
@ -370,6 +373,7 @@ TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
REQUIRE_THROWS(proxy.Call("vb_cs", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vb_cs", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_opa_fd", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vb_opa_fd", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcom_adc2", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vcom_adc2", {}, -1, GET));
// jungfrau
REQUIRE_THROWS(proxy.Call("vb_ds", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vb_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vb_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_pixbuf", {}, -1, GET)); REQUIRE_THROWS(proxy.Call("vb_pixbuf", {}, -1, GET));

View File

@ -0,0 +1,226 @@
#include "CmdProxy.h"
#include "Detector.h"
#include "catch.hpp"
#include "sls_detector_defs.h"
#include <sstream>
#include "Result.h"
#include "ToString.h"
#include "test-CmdProxy-global.h"
#include "tests/globals.h"
#include "versionAPI.h"
using sls::CmdProxy;
using sls::Detector;
using test::GET;
using test::PUT;
TEST_CASE("Setting and reading back GOTTHARD2 dacs", "[.cmd][.dacs]") {
// vref_h_adc, vb_comp_fe, vb_comp_adc, vcom_cds,
// vref_restore, vb_opa_1st, vref_comp_fe, vcom_adc1,
// vref_prech, vref_l_adc, vref_cds, vb_cs,
// vb_opa_fd, vcom_adc2
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::GOTTHARD2) {
SECTION("vref_h_adc") { test_dac(defs::VREF_H_ADC, "vref_h_adc", 2099); }
SECTION("vb_comp_fe") { test_dac(defs::VB_COMP_FE, "vb_comp_fe", 0); }
SECTION("vb_comp_adc") { test_dac(defs::VB_COMP_ADC, "vb_comp_adc", 0); }
SECTION("vcom_cds") { test_dac(defs::VCOM_CDS, "vcom_cds", 1400); }
SECTION("vref_rstore") { test_dac(defs::VREF_RSTORE, "vref_rstore", 640); }
SECTION("vb_opa_1st") { test_dac(defs::VB_OPA_1ST, "vb_opa_1st", 0); }
SECTION("vref_comp_fe") { test_dac(defs::VREF_COMP_FE, "vref_comp_fe", 0); }
SECTION("vcom_adc1") { test_dac(defs::VCOM_ADC1, "vcom_adc1", 1400); }
SECTION("vref_prech") { test_dac(defs::VREF_PRECH, "vref_prech", 1720); }
SECTION("vref_l_adc") { test_dac(defs::VREF_L_ADC, "vref_l_adc", 700); }
SECTION("vref_cds") { test_dac(defs::VREF_CDS, "vref_cds", 1200); }
SECTION("vb_cs") { test_dac(defs::VB_CS, "vb_cs", 2799); }
SECTION("vb_opa_fd") { test_dac(defs::VB_OPA_FD, "vb_opa_fd", 0); }
SECTION("vcom_adc2") { test_dac(defs::VCOM_ADC2, "vcom_adc2", 1400); }
// eiger
REQUIRE_THROWS(proxy.Call("vthreshold", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vsvp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vsvn", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vtr", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vrf", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vrs", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vtgstv", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_ll", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_lr", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcal", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_rl", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_rr", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("rxb_rb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("rxb_lb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcn", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vis", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("iodelay", {}, -1, GET));
// gotthard
REQUIRE_THROWS(proxy.Call("vref_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascn_pb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascp_pb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vout_cm", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcasc_out", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vin_cm", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("ib_test_c", {}, -1, GET));
// jungfrau
REQUIRE_THROWS(proxy.Call("vb_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_pixbuf", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vin_com", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vdd_prot", {}, -1, GET));
// mythen3
REQUIRE_THROWS(proxy.Call("vpreamp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vshaper", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vshaperneg", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vipre", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("viinsh", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vdcsh", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vth1", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vth2", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vth3", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vpl", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vph", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vtrim", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcassh", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcas", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vicin", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vipre_out", {}, -1, GET));
}
}
TEST_CASE("vchip", "[.cmd][.onchipdacs]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::GOTTHARD2) {
std::vector<std::string> on_chip_dac_names = {"vchip_comp_fe", "vchip_opa_1st", "vchip_opa_fd", "vchip_comp_adc", "vchip_ref_comp_fe", "vchip_cs"};
std::vector<defs::dacIndex> on_chip_dac_indices = {defs::VB_COMP_FE, defs::VB_OPA_1ST, defs::VB_OPA_FD, defs::VB_COMP_ADC, defs::VREF_COMP_FE, defs::VB_CS};
std::vector<int> values = {0x137, 0x000, 0x134, 0x3FF, 0x100, 0x0D0};
for (size_t i = 0; i < on_chip_dac_names.size(); ++i) {
REQUIRE_THROWS(proxy.Call(on_chip_dac_names[i], {}, -1, GET));
REQUIRE_THROWS(proxy.Call(on_chip_dac_names[i], {"10", "0x0"}, -1, GET)); // chip index (-1 to 9)
REQUIRE_THROWS(proxy.Call(on_chip_dac_names[i], {"-1", "0x400"}, -1, GET)); // max val is 0x3ff
auto previous = det.getOnChipDAC(on_chip_dac_indices[i], -1);
auto dacstr = sls::ToStringHex(values[i]);
int chip_index = -1;
auto chip_index_str = std::to_string(chip_index);
std::ostringstream oss_set, oss_get;
proxy.Call(on_chip_dac_names[i], {chip_index_str, dacstr}, -1, PUT, oss_set);
REQUIRE(oss_set.str() == on_chip_dac_names[i] + " " + chip_index_str + " " + dacstr + "\n");
proxy.Call(on_chip_dac_names[i], {chip_index_str}, -1, GET, oss_get);
REQUIRE(oss_get.str() == on_chip_dac_names[i] + " " + chip_index_str + " " + dacstr + "\n");
// Reset all dacs to previous value
for (int i = 0; i != det.size(); ++i) {
det.setOnChipDAC(on_chip_dac_indices[i], chip_index, previous[i], {i});
}
}
} else {
REQUIRE_THROWS(proxy.Call("vchip_comp_fe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vchip_opa_1st", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vchip_opa_fd", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vchip_comp_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vchip_ref_comp_fe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vchip_cs", {}, -1, GET));
}
}
TEST_CASE("burstmode", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::GOTTHARD2) {
auto burst = det.getBurstMode();
auto burststr = sls::ToString(burst);
{
std::ostringstream oss;
proxy.Call("burstmode", {"internal"}, -1, PUT, oss);
REQUIRE(oss.str() == "burstmode internal\n");
}
{
std::ostringstream oss;
proxy.Call("burstmode", {"off"}, -1, PUT, oss);
REQUIRE(oss.str() == "burstmode off\n");
}
{
std::ostringstream oss;
proxy.Call("burstmode", {}, -1, GET, oss);
REQUIRE(oss.str() == "burstmode off\n");
}
for (int i = 0; i != det.size(); ++i) {
det.setBurstMode(burst[i], {i});
}
} else {
REQUIRE_THROWS(proxy.Call("burstmode", {}, -1, GET));
}
}
TEST_CASE("vetoref", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::GOTTHARD2) {
REQUIRE_THROWS(proxy.Call("vetoref", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vetoref", {"3", "0x3ff"}, -1, PUT)); // invalid chip index
REQUIRE_NOTHROW(proxy.Call("vetoref", {"1", "0x010"}, -1, PUT));
} else {
REQUIRE_THROWS(proxy.Call("vetoref", {"3", "0x0"}, -1, PUT));
}
}
TEST_CASE("vetophoton", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::GOTTHARD2) {
REQUIRE_THROWS(proxy.Call("vetophoton", {}, -1, GET));
REQUIRE_NOTHROW(proxy.Call("vetophoton", {"-1"}, -1, GET));
REQUIRE_THROWS(proxy.Call("vetophoton", {"12", "1", "39950"}, -1, PUT));// invalid chip index
REQUIRE_THROWS(proxy.Call("vetophoton", {"-1", "0"}, -1, PUT)); // invalid photon number
REQUIRE_THROWS(proxy.Call("vetophoton", {"-1", "1", "39950"}, -1, PUT)); // invald file
} else {
REQUIRE_THROWS(proxy.Call("vetophoton", {"-1"}, -1, GET));
}
}
TEST_CASE("inj_ch", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::GOTTHARD2) {
auto inj = det.getInjectChannel();
REQUIRE_THROWS(proxy.Call("inj_ch", {"-1", "1"}, -1, PUT));// invalid offset
REQUIRE_THROWS(proxy.Call("inj_ch", {"0", "0"}, -1, PUT));// invalid increment
{
std::ostringstream oss;
proxy.Call("inj_ch", {"0", "1"}, -1, PUT, oss);
REQUIRE(oss.str() == "inj_ch [0, 1]\n");
}
{
std::ostringstream oss;
proxy.Call("inj_ch", {}, -1, GET, oss);
REQUIRE(oss.str() == "inj_ch [0, 1]\n");
}
for (int i = 0; i != det.size(); ++i) {
det.setInjectChannel(inj[i][0], inj[i][1], {i});
}
} else {
REQUIRE_THROWS(proxy.Call("inj_ch", {}, -1, GET));
}
}

View File

@ -479,58 +479,3 @@ TEST_CASE("rx_zmqip", "[.cmd]") {
} }
} }
// TEST_CASE("burstmode", "[.cmd][.gotthard2]") {
// if (test::type == slsDetectorDefs::GOTTHARD2) {
// REQUIRE_NOTHROW(multiSlsDetectorClient("burstmode 0", PUT));
// REQUIRE_NOTHROW(multiSlsDetectorClient("burstmode 1", PUT));
// REQUIRE_NOTHROW(multiSlsDetectorClient("burstmode", GET));
// } else {
// REQUIRE_THROWS(multiSlsDetectorClient("burstmod", GET));
// }
// }
// TEST_CASE("vetoref", "[.cmd][.gotthard2]") {
// if (test::type == slsDetectorDefs::GOTTHARD2) {
// REQUIRE_THROWS(multiSlsDetectorClient("vetoref 3 0x3ff", PUT)); //
// invalid chip index REQUIRE_THROWS(multiSlsDetectorClient("vetoref 0
// 0xFFFF", PUT)); // invalid value
// REQUIRE_NOTHROW(multiSlsDetectorClient("vetoref 1 0x010", PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("vetoref", GET));
// } else {
// REQUIRE_THROWS(multiSlsDetectorClient("vetoref 3 0x0", PUT));
// }
// }
// TEST_CASE("vetophoton", "[.cmd][.gotthard2]") {
// if (test::type == slsDetectorDefs::GOTTHARD2) {
// REQUIRE_THROWS(multiSlsDetectorClient("vetophoton 12 1 39950
// examples/gotthard2_veto_photon.txt", PUT)); // invalid chip index
// REQUIRE_THROWS(multiSlsDetectorClient("vetophoton -1 0 39950
// examples/gotthard2_veto_photon.txt", PUT)); // invalid photon number
// REQUIRE_NOTHROW(multiSlsDetectorClient("vetophoton -1 1 39950
// examples/gotthard2_veto_photon.txt", PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("vetophoton", GET));
// REQUIRE_NOTHROW(multiSlsDetectorClient("vetophoton -1", GET));
// } else {
// REQUIRE_THROWS(multiSlsDetectorClient("vetophoton -1", GET));
// }
// }
// TEST_CASE("inj_ch", "[.cmd][.gotthard2]") {
// if (test::type == slsDetectorDefs::GOTTHARD2) {
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("inj_ch 0 1", PUT,
// nullptr, oss)); REQUIRE(oss.str() == "inj_ch [0, 1]\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("inj_ch", GET, nullptr,
// oss)); REQUIRE(oss.str() == "inj_ch [0, 1]\n");
// }
// REQUIRE_THROWS(multiSlsDetectorClient("inj_ch -1 1", PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("inj_ch 0 0", PUT));
// } else {
// REQUIRE_THROWS(multiSlsDetectorClient("inj_ch", GET));
// }
// }

View File

@ -34,120 +34,35 @@ TEST_CASE("type", "[.cmd]"){
} }
// TEST_CASE("vchip", "[.cmd]") {
// int prev_val = 0;
// if (test::type == slsDetectorDefs::GOTTHARD2) { TEST_CASE("initialchecks", "[.cmd]") {
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_comp_fe", GET)); // Detector det;
// needs a chip index CmdProxy proxy(&det);
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_comp_fe -1 0x400", auto check = det.getInitialChecks();
// GET)); // max val is 0x3ff auto dtstr = sls::ToString(check);
// { auto hostname = det.getHostname();
// std::ostringstream oss; std::string hostnamestr;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_fe -1", GET, for (auto &it : hostname) {
// nullptr, oss)); std::string s = (oss.str()).erase (0, hostnamestr += (it + "+");
// strlen("vchip_comp_fe -1 ")); prev_val = stoul(s, 0, 16); }
// } {
// { std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_fe -1 0x137", proxy.Call("initialchecks", {"0"}, -1, PUT, oss);
// PUT)); std::ostringstream oss; REQUIRE(oss.str() == "initialchecks 0\n");
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_fe -1", GET, }
// nullptr, oss)); REQUIRE(oss.str() == "vchip_comp_fe -1 0x137\n"); {
// } std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_fe -1 " + proxy.Call("initialchecks", {}, -1, GET, oss);
// sls::ToStringHex(prev_val), PUT)); REQUIRE(oss.str() == "initialchecks 0\n");
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_opa_1st", GET)); // }
// needs a chip index {
// { det.setHostname(hostname);
// std::ostringstream oss; std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_1st -1", GET, proxy.Call("initialchecks", {}, -1, GET, oss);
// nullptr, oss)); std::string s = (oss.str()).erase (0, REQUIRE(oss.str() == "initialchecks 0\n");
// strlen("vchip_opa_1st -1 ")); prev_val = stoul(s, 0, 16); }
// } det.setInitialChecks(check);
// { }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_1st -1 0x137",
// PUT)); std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_1st -1", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vchip_opa_1st -1 0x137\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_1st -1 " +
// sls::ToStringHex(prev_val), PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_opa_fd", GET)); // needs
// a chip index
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_fd -1", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vchip_opa_fd -1 ")); prev_val = stoul(s, 0, 16);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_fd -1 0x137",
// PUT)); std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_fd -1", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vchip_opa_fd -1 0x137\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_opa_fd -1 " +
// sls::ToStringHex(prev_val), PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_comp_adc", GET)); //
// needs a chip index
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_adc -1", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vchip_comp_adc -1 ")); prev_val = stoul(s, 0, 16);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_adc -1 0x137",
// PUT)); std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_adc -1", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vchip_comp_adc -1
// 0x137\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_comp_adc -1 " +
// sls::ToStringHex(prev_val), PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_ref_comp_fe", GET)); //
// needs a chip index
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_ref_comp_fe -1",
// GET, nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vchip_ref_comp_fe -1 ")); prev_val = stoul(s, 0, 16);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_ref_comp_fe -1
// 0x137", PUT)); std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_ref_comp_fe -1",
// GET, nullptr, oss)); REQUIRE(oss.str() == "vchip_ref_comp_fe -1
// 0x137\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_ref_comp_fe -1 " +
// sls::ToStringHex(prev_val), PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_cs", GET)); // needs a
// chip index
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_cs -1", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vchip_cs -1 ")); prev_val = stoul(s, 0, 16);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_cs -1 0x137",
// PUT)); std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_cs -1", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vchip_cs -1 0x137\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vchip_cs -1 " +
// sls::ToStringHex(prev_val), PUT));
// } else {
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_comp_fe", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_opa_1st", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_opa_fd", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_comp_adc", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_ref_comp_fe", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vchip_cs", GET));
// }
// }
// TEST_CASE("dacs", "[.cmd]") { // TEST_CASE("dacs", "[.cmd]") {
// REQUIRE_NOTHROW(multiSlsDetectorClient("daclist", GET)); // REQUIRE_NOTHROW(multiSlsDetectorClient("daclist", GET));
@ -574,238 +489,6 @@ TEST_CASE("type", "[.cmd]"){
// REQUIRE_THROWS(multiSlsDetectorClient("vdd_prot", GET)); // REQUIRE_THROWS(multiSlsDetectorClient("vdd_prot", GET));
// } // }
// else if (test::type == slsDetectorDefs::GOTTHARD2) {
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_h_adc", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vref_h_adc ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_h_adc 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_h_adc", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vref_h_adc 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_h_adc " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_fe", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vb_comp_fe ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_fe 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_fe", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vb_comp_fe 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_fe " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_adc", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vb_comp_adc ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_adc 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_adc", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vb_comp_adc 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_comp_adc " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_cds", GET, nullptr,
// oss)); std::string s = (oss.str()).erase (0, strlen("vcom_cds
// ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_cds 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_cds", GET, nullptr,
// oss)); REQUIRE(oss.str() == "vcom_cds 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_cds " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_rstore", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vref_rstore ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_rstore 1000",
// PUT)); std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_rstore", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vref_rstore 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_rstore " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_1st", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vb_opa_1st ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_1st 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_1st", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vb_opa_1st 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_1st " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_comp_fe", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vref_comp_fe ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_comp_fe 1000",
// PUT)); std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_comp_fe", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vref_comp_fe 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_comp_fe " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc1", GET, nullptr,
// oss)); std::string s = (oss.str()).erase (0, strlen("vcom_adc1
// ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc1 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc1", GET, nullptr,
// oss)); REQUIRE(oss.str() == "vcom_adc1 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc1 " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_prech", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vref_prech ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_prech 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_prech", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vref_prech 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_prech " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_l_adc", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("vref_l_adc ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_l_adc 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_l_adc", GET,
// nullptr, oss)); REQUIRE(oss.str() == "vref_l_adc 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_l_adc " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_cds", GET, nullptr,
// oss)); std::string s = (oss.str()).erase (0, strlen("vref_cds
// ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_cds 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_cds", GET, nullptr,
// oss)); REQUIRE(oss.str() == "vref_cds 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vref_cds " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_cs", GET, nullptr,
// oss)); std::string s = (oss.str()).erase (0, strlen("vb_cs "));
// prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_cs 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_cs", GET, nullptr,
// oss)); REQUIRE(oss.str() == "vb_cs 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_cs " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_fd", GET, nullptr,
// oss)); std::string s = (oss.str()).erase (0, strlen("vb_opa_fd
// ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_fd 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_fd", GET, nullptr,
// oss)); REQUIRE(oss.str() == "vb_opa_fd 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vb_opa_fd " +
// std::to_string(prev_val), PUT));
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc2", GET, nullptr,
// oss)); std::string s = (oss.str()).erase (0, strlen("vcom_adc2
// ")); prev_val = std::stoi(s);
// }
// {
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc2 1000", PUT));
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc2", GET, nullptr,
// oss)); REQUIRE(oss.str() == "vcom_adc2 1000\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("vcom_adc2 " +
// std::to_string(prev_val), PUT));
// REQUIRE_THROWS(multiSlsDetectorClient("vthreshold", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vsvp", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vsvn", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vtr", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vrf", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vrs", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vtgstv", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcmp_ll", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcmp_lr", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcal", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcmp_rl", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcmp_rr", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("rxb_rb", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("rxb_lb", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcp", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcn", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vis", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("iodelay", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vref_ds", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcascn_pb", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcascp_pb", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vout_cm", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vcasc_out", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vin_cm", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vref_comp", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("ib_test_c", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vb_ds", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vb_comp", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vb_pixbuf", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vin_com", GET));
// REQUIRE_THROWS(multiSlsDetectorClient("vdd_prot", GET));
// }
// } // }
TEST_CASE("user", "[.cmd]") { TEST_CASE("user", "[.cmd]") {
@ -2340,7 +2023,7 @@ TEST_CASE("stopport", "[.cmd]") {
// REQUIRE_NOTHROW(multiSlsDetectorClient("0:flippeddatax", GET, // REQUIRE_NOTHROW(multiSlsDetectorClient("0:flippeddatax", GET,
// nullptr, oss)); REQUIRE(oss.str() == "flippeddatax 0\n"); // nullptr, oss)); REQUIRE(oss.str() == "flippeddatax 0\n");
// } // }
// multiSlsDetector d; // DetectorImpl d;
// if (d.size() > 1) { // if (d.size() > 1) {
// std::ostringstream oss; // std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("1:flippeddatax", GET, // REQUIRE_NOTHROW(multiSlsDetectorClient("1:flippeddatax", GET,
@ -2618,7 +2301,7 @@ TEST_CASE("fformat", "[.cmd]") {
// oss)); REQUIRE(oss.str() == "udp_dstport 6200\n"); // oss)); REQUIRE(oss.str() == "udp_dstport 6200\n");
// } // }
// { // {
// multiSlsDetector d; // DetectorImpl d;
// int socketsperdetector = 1; // int socketsperdetector = 1;
// if (test::type == slsDetectorDefs::EIGER) { // if (test::type == slsDetectorDefs::EIGER) {
// socketsperdetector *= 2; // socketsperdetector *= 2;

View File

@ -70,7 +70,7 @@ set_target_properties(slsReceiverShared PROPERTIES
) )
add_executable(slsReceiver add_executable(slsReceiver
src/main.cpp) src/ReceiverApp.cpp)
set_target_properties(slsReceiver PROPERTIES set_target_properties(slsReceiver PROPERTIES
@ -88,7 +88,7 @@ target_link_libraries(slsReceiver PUBLIC
) )
add_executable(slsMultiReceiver add_executable(slsMultiReceiver
src/multiReceiver.cpp) src/MultiReceiverApp.cpp)
set_target_properties(slsMultiReceiver PROPERTIES set_target_properties(slsMultiReceiver PROPERTIES

View File

@ -0,0 +1,129 @@
#pragma once
/* CircularFifo.h
* Code & platform dependent issues with it was originally
* published at http://www.kjellkod.cc/threadsafecircularqueue
* 2009-11-02
* @author Kjell Hedstr<EFBFBD>m, hedstrom@kjellkod.cc
* modified by the sls detector group
* */
#include <iostream>
#include <semaphore.h>
#include <vector>
/** Circular Fifo (a.k.a. Circular Buffer)
* Thread safe for one reader, and one writer */
template <typename Element> class CircularFifo {
private:
size_t tail{0};
size_t head{0};
size_t capacity;
std::vector<Element *> data;
mutable sem_t data_mutex;
mutable sem_t free_mutex;
size_t increment(size_t i) const;
public:
explicit CircularFifo(size_t size) : capacity(size + 1), data(capacity) {
sem_init(&data_mutex, 0, 0);
sem_init(&free_mutex, 0, size);
}
CircularFifo(const CircularFifo &) = delete;
CircularFifo(CircularFifo&&) = delete;
virtual ~CircularFifo() {
sem_destroy(&data_mutex);
sem_destroy(&free_mutex);
}
bool push(Element *&item, bool no_block = false);
bool pop(Element *&item, bool no_block = false);
bool isEmpty() const;
bool isFull() const;
int getDataValue() const;
int getFreeValue() const;
};
template <typename Element> int CircularFifo<Element>::getDataValue() const {
int value;
sem_getvalue(&data_mutex, &value);
return value;
}
template <typename Element> int CircularFifo<Element>::getFreeValue() const {
int value;
sem_getvalue(&free_mutex, &value);
return value;
}
/** Producer only: Adds item to the circular queue.
* If queue is full at 'push' operation no update/overwrite
* will happen, it is up to the caller to handle this case
*
* \param item_ copy by reference the input item
* \param no_block if true, return immediately if fifo is full
* \return whether operation was successful or not */
template <typename Element>
bool CircularFifo<Element>::push(Element *&item, bool no_block) {
// check for fifo full
if (no_block && isFull())
return false;
sem_wait(&free_mutex);
data[tail] = item;
tail = increment(tail);
sem_post(&data_mutex);
return true;
}
/** Consumer only: Removes and returns item from the queue
* If queue is empty at 'pop' operation no retrieve will happen
* It is up to the caller to handle this case
*
* \param item_ return by reference the wanted item
* \param no_block if true, return immediately if fifo is full
* \return whether operation was successful or not */
template <typename Element>
bool CircularFifo<Element>::pop(Element *&item, bool no_block) {
// check for fifo empty
if (no_block && isEmpty())
return false;
sem_wait(&data_mutex);
item = data[head];
head = increment(head);
sem_post(&free_mutex);
return true;
}
/** Useful for testing and Consumer check of status
* Remember that the 'empty' status can change quickly
* as the Producer adds more items.
*
* \return true if circular buffer is empty */
template <typename Element> bool CircularFifo<Element>::isEmpty() const {
return (getDataValue() == 0);
}
/** Useful for testing and Producer check of status
* Remember that the 'full' status can change quickly
* as the Consumer catches up.
*
* \return true if circular buffer is full. */
template <typename Element> bool CircularFifo<Element>::isFull() const {
return (getFreeValue() == 0);
}
/** Increment helper function for index of the circular queue
* index is incremented or wrapped
*
* \param idx_ the index to the incremented/wrapped
* \return new value for the index */
template <typename Element>
size_t CircularFifo<Element>::increment(size_t i) const {
i = (i + 1) % capacity;
return i;
}

View File

@ -1,160 +0,0 @@
#pragma once
#include "receiver_defs.h"
#include "sls_detector_defs.h"
#include "Implementation.h"
#include "ServerSocket.h"
class MySocketTCP;
class ServerInterface;
#include <atomic>
#include <future>
class ClientInterface : private virtual slsDetectorDefs {
private:
enum numberMode { DEC, HEX };
public:
virtual ~ClientInterface();
ClientInterface(int portNumber = -1);
int64_t getReceiverVersion();
//***callback functions***
/** params: filepath, filename, fileindex, datasize */
void registerCallBackStartAcquisition(int (*func)(std::string, std::string, uint64_t,
uint32_t, void *),
void *arg);
/** params: total frames caught */
void registerCallBackAcquisitionFinished(void (*func)(uint64_t, void *),
void *arg);
/** params: sls_receiver_header frame metadata, dataPointer, dataSize */
void registerCallBackRawDataReady(void (*func)(char *, char *, uint32_t,
void *),
void *arg);
/** params: sls_receiver_header frame metadata, dataPointer, modified size */
void registerCallBackRawDataModifyReady(void (*func)(char *, char *,
uint32_t &, void *),
void *arg);
private:
void startTCPServer();
int functionTable();
int decodeFunction(sls::ServerInterface2 &socket);
void functionNotImplemented();
void modeNotImplemented(const std::string& modename, int mode);
template <typename T>
void validate(T arg, T retval, std::string modename, numberMode hex);
void verifyLock();
void verifyIdle(sls::ServerInterface2 &socket);
int exec_command(sls::ServerInterface2 &socket);
int exit_server(sls::ServerInterface2 &socket);
int lock_receiver(sls::ServerInterface2 &socket);
int get_last_client_ip(sls::ServerInterface2 &socket);
int set_port(sls::ServerInterface2 &socket);
int update_client(sls::ServerInterface2 &socket);
int send_update(sls::ServerInterface2 &socket);
int get_version(sls::ServerInterface2 &socket);
int set_detector_type(sls::ServerInterface2 &socket);
int set_detector_hostname(sls::ServerInterface2 &socket);
int set_roi(sls::ServerInterface2 &socket);
int set_num_frames(sls::ServerInterface2 &socket);
int set_num_analog_samples(sls::ServerInterface2 &socket);
int set_num_digital_samples(sls::ServerInterface2 &socket);
int set_exptime(sls::ServerInterface2 &socket);
int set_period(sls::ServerInterface2 &socket);
int set_subexptime(sls::ServerInterface2 &socket);
int set_subdeadtime(sls::ServerInterface2 &socket);
int set_dynamic_range(sls::ServerInterface2 &socket);
int set_streaming_frequency(sls::ServerInterface2 &socket);
int get_status(sls::ServerInterface2 &socket);
int start_receiver(sls::ServerInterface2 &socket);
int stop_receiver(sls::ServerInterface2 &socket);
int set_file_dir(sls::ServerInterface2 &socket);
int set_file_name(sls::ServerInterface2 &socket);
int set_file_index(sls::ServerInterface2 &socket);
int get_frame_index(sls::ServerInterface2 &socket);
int get_missing_packets(sls::ServerInterface2 &socket);
int get_frames_caught(sls::ServerInterface2 &socket);
int enable_file_write(sls::ServerInterface2 &socket);
int enable_master_file_write(sls::ServerInterface2 &socket);
int enable_compression(sls::ServerInterface2 &socket);
int enable_overwrite(sls::ServerInterface2 &socket);
int enable_tengiga(sls::ServerInterface2 &socket);
int set_fifo_depth(sls::ServerInterface2 &socket);
int set_activate(sls::ServerInterface2 &socket);
int set_data_stream_enable(sls::ServerInterface2 &socket);
int set_streaming_timer(sls::ServerInterface2 &socket);
int set_flipped_data(sls::ServerInterface2 &socket);
int set_file_format(sls::ServerInterface2 &socket);
int set_detector_posid(sls::ServerInterface2 &socket);
int set_multi_detector_size(sls::ServerInterface2 &socket);
int set_streaming_port(sls::ServerInterface2 &socket);
int set_streaming_source_ip(sls::ServerInterface2 &socket);
int set_silent_mode(sls::ServerInterface2 &socket);
int enable_gap_pixels(sls::ServerInterface2 &socket);
int restream_stop(sls::ServerInterface2 &socket);
int set_additional_json_header(sls::ServerInterface2 &socket);
int get_additional_json_header(sls::ServerInterface2 &socket);
int set_udp_socket_buffer_size(sls::ServerInterface2 &socket);
int get_real_udp_socket_buffer_size(sls::ServerInterface2 &socket);
int set_frames_per_file(sls::ServerInterface2 &socket);
int check_version_compatibility(sls::ServerInterface2 &socket);
int set_discard_policy(sls::ServerInterface2 &socket);
int set_padding_enable(sls::ServerInterface2 &socket);
int set_deactivated_padding_enable(sls::ServerInterface2 &socket);
int set_readout_mode(sls::ServerInterface2 &socket);
int set_adc_mask(sls::ServerInterface2 &socket);
int set_dbit_list(sls::ServerInterface2 &socket);
int get_dbit_list(sls::ServerInterface2 &socket);
int set_dbit_offset(sls::ServerInterface2 &socket);
int set_quad_type(sls::ServerInterface2 &socket);
int set_read_n_lines(sls::ServerInterface2 &socket);
int set_udp_ip(sls::ServerInterface2 &socket);
int set_udp_ip2(sls::ServerInterface2 &socket);
int set_udp_port(sls::ServerInterface2 &socket);
int set_udp_port2(sls::ServerInterface2 &socket);
int set_num_interfaces(sls::ServerInterface2 &socket);
int set_adc_mask_10g(sls::ServerInterface2 &socket);
int set_num_counters(sls::ServerInterface2 &socket);
Implementation *impl() {
if (receiver != nullptr) {
return receiver.get();
} else {
throw sls::SocketError(
"Receiver not set up. Please use rx_hostname first.\n");
}
}
detectorType myDetectorType;
std::unique_ptr<Implementation> receiver{nullptr};
int (ClientInterface::*flist[NUM_REC_FUNCTIONS])(
sls::ServerInterface2 &socket);
int ret{OK};
int fnum{-1};
int lockedByClient{0};
int portNumber{0};
std::atomic<bool> killTcpThread{false};
std::unique_ptr<std::thread> tcpThread;
//***callback parameters***
int (*startAcquisitionCallBack)(std::string, std::string, uint64_t, uint32_t,
void *) = nullptr;
void *pStartAcquisition{nullptr};
void (*acquisitionFinishedCallBack)(uint64_t, void *) = nullptr;
void *pAcquisitionFinished{nullptr};
void (*rawDataReadyCallBack)(char *, char *, uint32_t, void *) = nullptr;
void (*rawDataModifyReadyCallBack)(char *, char *, uint32_t &,
void *) = nullptr;
void *pRawDataReady{nullptr};
protected:
std::unique_ptr<sls::ServerSocket> server{nullptr};
};

View File

@ -1,9 +1,9 @@
#pragma once #pragma once
#include "ClientInterface.h"
#include "sls_detector_defs.h" #include "sls_detector_defs.h"
#include <memory> #include <memory>
class ClientInterface;
class Receiver : private virtual slsDetectorDefs { class Receiver : private virtual slsDetectorDefs {
public: public:
@ -26,6 +26,8 @@ class Receiver : private virtual slsDetectorDefs {
*/ */
Receiver(int tcpip_port_no = 1954); Receiver(int tcpip_port_no = 1954);
~Receiver();
/** /**
* get get Receiver Version * get get Receiver Version
\returns id \returns id

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