Compare commits

..

1 Commits
khalil ... pip

Author SHA1 Message Date
acf2ab4295 moved .so into package 2023-08-24 11:50:33 +02:00
190 changed files with 10729 additions and 184121 deletions

View File

@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v3
- uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: libhdf5-dev qtbase5-dev qt5-qmake libqt5svg5-dev
packages: libzmq3-dev libhdf5-dev qtbase5-dev qt5-qmake libqt5svg5-dev
version: 1.0
- name: Configure CMake

View File

@ -1 +0,0 @@
# This file is generated by cmake for dependency checking of the CMakeCache.txt file

View File

@ -244,7 +244,6 @@ if(SLS_USE_SANITIZER)
# target_link_libraries(slsProjectOptions INTERFACE -fsanitize=thread)
endif()
if(SLS_TUNE_LOCAL)
target_compile_options(slsProjectOptions INTERFACE -mtune=native -march=native)
endif()
@ -295,7 +294,7 @@ if (SLS_USE_INTEGRATION_TESTS)
endif (SLS_USE_INTEGRATION_TESTS)
if (SLS_USE_PYTHON)
find_package (Python 3.6 COMPONENTS Interpreter Development)
find_package (Python 3.6 COMPONENTS Interpreter Development.Module)
if(SLS_FETCH_PYBIND11_FROM_GITHUB)
FetchContent_Declare(
pybind11

View File

@ -1 +0,0 @@
slsDetectorSoftware/generator/autocomplete/bash_autocomplete.sh

2
cmk.sh
View File

@ -26,7 +26,7 @@ CMAKE_PRE=""
CMAKE_POST=""
usage() { echo -e "
Usage: $0 [-b] [-c] [-d <HDF5 directory>] [-e] [-g] [-h] [-i] [-j <Number of threads>] [-k <CMake command>] [-l <Install directory>] [-m] [-n] [-p] [-r] [-s] [-t] [-u] [-z]
Usage: $0 [-b] [-c] [-d <HDF5 directory>] [e] [g] [-h] [i] [-j <Number of threads>] [-k <CMake command>] [-l <Install directory>] [m] [n] [-p] [r] [s] [t] [u] [z]
-[no option]: only make
-b: Builds/Rebuilds CMake files normal mode
-c: Clean

View File

@ -2,6 +2,7 @@ python:
- 3.8
- 3.9
- 3.10
- 3.11
- 3.12
- 3.11
numpy:
- 1.17

View File

@ -18,6 +18,7 @@ requirements:
- {{compiler('cxx')}}
- cmake
- qt 5.*
- zeromq
- xorg-libx11
- xorg-libice
- xorg-libxext
@ -36,6 +37,7 @@ requirements:
host:
- libstdcxx-ng
- libgcc-ng
- zeromq
- xorg-libx11
- xorg-libice
- xorg-libxext
@ -46,6 +48,7 @@ requirements:
- expat
run:
- zeromq
- libstdcxx-ng
- libgcc-ng
@ -60,11 +63,15 @@ outputs:
- {{compiler('cxx')}}
- libstdcxx-ng
- libgcc-ng
- zeromq
host:
- zeromq
run:
- libstdcxx-ng
- libgcc-ng
- zeromq
- name: slsdet
@ -77,12 +84,10 @@ outputs:
- {{compiler('cxx')}}
- {{ pin_subpackage('slsdetlib', exact=True) }}
- setuptools
- pybind11=2.11
host:
- python
- {{ pin_subpackage('slsdetlib', exact=True) }}
- pybind11=2.11
run:

View File

@ -19,7 +19,7 @@ A minimal CMakeLists.txt could look like this:
.. code-block:: cmake
project(myDetectorIntegration)
cmake_minimum_required(VERSION 3.14)
cmake_minimum_required(VERSION 3.12)
add_subdirectory(slsDetectorPackage)
#Add your executable
@ -43,7 +43,7 @@ should be needed, otherwise specify cmake prefix path.
.. code-block:: cmake
cmake_minimum_required(VERSION 3.14)
cmake_minimum_required(VERSION 3.12)
project(myintegration)
find_package(slsDetectorPackage 5.0 REQUIRED)

View File

@ -13,36 +13,24 @@ To use the basic building blocks, meaning sls_detector_get/put and
the shared libraries these are needed:
* Linux, preferably recent kernel (currently no cross platform support)
* CMake >= 3.14
* CMake > 3.12
* C++11 compatible compiler. (We test with gcc and clang)
-----------------------
Python bindings
-----------------------
* Python > 3.6
* pybind11 2.11.0 (packaged in libs)
.. note ::
Refer :ref:`pybind11 notes. <pybind for different slsDetectorPackage versions>`
-----------------------
ZeroMQ
-----------------------
* Zeromq 4.3.4 (packaged in libs)
.. note ::
Refer :ref:`zeromq notes. <zeromq for different slsDetectorPackage versions>`
* ZeroMQ version 4
-----------------------
GUI
-----------------------
* Qt 5.9
* Qwt 6.1.5 (packaged in libs)
* Qwt 6.1.5 (packaged in libs/)
-----------------------
Python bindings
-----------------------
* Python > 3.6
* pybind11 (packaged in libs/)
-----------------------
Moench executables
@ -66,6 +54,4 @@ Packaged in libs/
* catch2 (unit testing)
* rapidjson (streaming from receiver)
* pybind11 (python bindings)
* qwt (gui plotting)
* libzmq (streaming to/from receiver)
* pybind11 (python bindings)

View File

@ -1,19 +1,16 @@
Detector
==============================================
The sls::Detector is the public API to control
The sls::Detector is the new public API to control
detectors from C++. This API is also used internally
for the Python bindings and the command line interface.
If a receiver has been configured, this is also controlled
If a receiver has been configured this is also controlled
through this class.
Most, if not all, functions are called in parallel
and the return value is a thin std::vector wrapper
containing results from all modules. (:ref:`Result class<Result Class>`)
containing results from all modules. (Result<T>)
Here are some :ref:`examples <Cplusplus Api Examples>` on how to use the API.
.. _Cplusplus Api Examples:
.. doxygenclass:: sls::Detector
:members:
:undoc-members:

View File

@ -1,4 +1,3 @@
.. _Cplusplus Api Examples:
@ -54,8 +53,8 @@ then set up the detector.
jungfrauDetectorServer_virtual
This launches a virtual Jungfrau detector server. As default it uses port 1952 and 1953
for communication over TCP. Most commands go on 1952 and only a few such as stop and status on 1953.
This launches a virtual Jungfrau detector server. As default is uses port 1952 and 1953
for communication over TCP. Most commands go on 1952 and only stop and status on 1953.
**Run example to configure**
@ -91,10 +90,7 @@ std::vector.
sls::Result<int> res1{1, 1, 1};
std::cout << "res1: " << res1 << '\n';
res1.squash();
# return -1 if different
res1.squash(-1);
# throw exception with custom message if different
res1.tsquash("Values are different);

View File

@ -120,7 +120,7 @@ Program from console
# removes old server from respawn, sets up new lnked server to respawn
# programs fpga, reboots
# older versions: v5.0.0 - 6.0.0 using tftp from tftp folder of pc
# v5.0.0 - 6.0.0 (copies server from tftp folder of the pc)
sls_detector_put update jungfrauDetectorServervxxx pcxxx xx.pof
# v6.1.1 - present (copies server from the full path provided)
@ -190,7 +190,7 @@ Program from console
# removes old server from respawn, sets up new lnked server to respawn
# programs fpga, reboots
# older versions: v5.0.0 - 6.0.0 using tftp from tftp folder of pc
# v5.0.0 - 6.0.0 (copies server from tftp folder of the pc)
sls_detector_put update mythen3DetectorServervxxx pcxxx xxx.rbf
# v6.1.1 - present (copies server from the full path provided)
@ -224,7 +224,7 @@ Program from console
# removes old server from respawn, sets up new lnked server to respawn
# programs fpga, reboots
# older versions: v5.0.0 - 6.0.0 using tftp from tftp folder of pc
# v5.0.0 - 6.0.0 (copies server from tftp folder of the pc)
sls_detector_put update gotthard2DetectorServervxxx pcxxx xxx.rbf
# v6.1.1 - present (copies server from the full path provided)
@ -275,7 +275,7 @@ Program from console
# removes old server from respawn, sets up new lnked server to respawn
# programs fpga, reboots
# older versions: v5.0.0 - 6.0.0 using tftp from tftp folder of pc
# v5.0.0 - 6.0.0 (copies server from tftp folder of the pc)
sls_detector_put update moenchDetectorServervxxx pcxxx xx.pof
# v6.1.1 - present (copies server from the full path provided)
@ -310,7 +310,7 @@ Program from console
# removes old server from respawn, sets up new lnked server to respawn
# programs fpga, reboots
# older versions: v5.0.0 - 6.0.0 using tftp from tftp folder of pc
# v5.0.0 - 6.0.0 (copies server from tftp folder of the pc)
sls_detector_put update ctbDetectorServervxxx pcxxx xx.pof
# v6.1.1 - present (copies server from the full path provided)

View File

@ -8,8 +8,8 @@ Welcome to slsDetectorPackage's documentation!
.. note ::
This is the documentation for the latest development version of slsDetectorPackage.
For further documentation, visit the official page: https://www.psi.ch/en/detectors/documentation
This is the documentation for the latest development version of slsDetectorPackage
For documentation on current and previous releases visit the official page: https://www.psi.ch/en/detectors/documentation
.. toctree::
:maxdepth: 1

View File

@ -57,6 +57,7 @@ We have three different packages available:
Build from source
-------------------
1. Download Source Code from github
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@ -64,9 +65,23 @@ Build from source
git clone https://github.com/slsdetectorgroup/slsDetectorPackage.git --branch 6.1.1
.. note ::
For v6.x.x of slsDetectorPackage and older, refer :ref:`pybind11 notes on cloning. <pybind for different slsDetectorPackage versions>`
| **Pybind for Python**
| v7.0.0+:
| pybind11 packaged into 'libs/pybind'. No longer a submodule. No need for "recursive" or "submodule update".
|
| Older versions:
| pybind11 is a submodule. Must be cloned using "recursive" and updated when switching between versions using the following commands.
.. code-block:: bash
# clone using recursive to get pybind11 submodule
git clone --recursive https://github.com/slsdetectorgroup/slsDetectorPackage.git
# update submodule when switching between releases
cd slsDetectorPackage
git submodule update --init
.. _build from source using cmake:
@ -103,23 +118,20 @@ Instead of the cmake command, one can use ccmake to get a list of options to con
ccmake ..
# choose the options
# first press [c] - configure (maybe multiple times till you see [g])
# first press [c] - configure
# then press [g] - generate
=============================== ===============================
=============================== ===========================================
Example cmake options Comment
=============================== ===============================
=============================== ===========================================
-DSLS_USE_PYTHON=ON Python
-DPython_FIND_VIRTUALENV=ONLY Python from the conda env
-DPython_FIND_VIRTUALENV=ONLY Python from only the conda environment
-DZeroMQ_HINT=/usr/lib64 Use system zmq instead
-DSLS_USE_GUI=ON GUI
-DSLS_USE_HDF5=ON HDF5
-DSLS_USE_SIMULATOR=ON Simulator
=============================== ===============================
=============================== ===========================================
.. note ::
For v7.x.x of slsDetectorPackage and older, refer :ref:`zeromq notes for cmake option to hint library location. <zeromq for different slsDetectorPackage versions>`
Build using in-built cmk.sh script
@ -130,9 +142,9 @@ Build using in-built cmk.sh script
The binaries are generated in slsDetectorPackage/build/bin directory.
Usage: $0 [-b] [-c] [-d <HDF5 directory>] [-e] [-g] [-h] [-i]
[-j <Number of threads>] [-k <CMake command>] [-l <Install directory>]
[-m] [-n] [-p] [-r] [-s] [-t] [-u] [-z]
Usage: ./cmk.sh [-b] [-c] [-d <HDF5 directory>] [e] [g] [-h] [i] [-j <Number of threads>]
[-k <CMake command>] [-l <Install directory>] [m] [n] [-p] [-q <Zmq hint directory>]
[r] [s] [t] [u] [z]
-[no option]: only make
-b: Builds/Rebuilds CMake files normal mode
-c: Clean
@ -147,6 +159,7 @@ Build using in-built cmk.sh script
-m: Manuals
-n: Manuals without compiling doxygen (only rst)
-p: Builds/Rebuilds Python API
-q: Zmq hint directory
-r: Build/Rebuilds only receiver
-s: Simulator
-t: Build/Rebuilds only text client
@ -163,13 +176,9 @@ Build using in-built cmk.sh script
# new build, python and compile in parallel:
./cmk.sh -cbpj5
#For rebuilding only certain sections
./cmk.sh -tg #only text client and gui
./cmk.sh -r #only receiver
#To use the system zmq (/usr/lib64) instead
./cmk.sh -cbj5 -q /usr/lib64
.. note ::
For v7.x.x of slsDetectorPackage and older, refer :ref:`zeromq notes for cmk script option to hint library location. <zeromq for different slsDetectorPackage versions>`
Build on old distributions
@ -182,7 +191,7 @@ using this compiler
.. code-block:: bash
#Create an environment with the dependencies
conda create -n myenv gxx_linux-64 cmake
conda create -n myenv gxx_linux-64 cmake zmq
conda activate myenv
# outside slsDetecorPackage folder
@ -191,11 +200,6 @@ using this compiler
make -j12
.. note ::
For v7.x.x of slsDetectorPackage and older, refer :ref:`zeromq notes for dependencies for conda. <zeromq for different slsDetectorPackage versions>`
Build slsDetectorGui (Qt5)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@ -224,9 +228,9 @@ Build slsDetectorGui (Qt5)
# create environment to compile
# on rhel7
conda create -n slsgui gxx_linux-64 gxx_linux-64 mesa-libgl-devel-cos6-x86_64 qt
conda create -n slsgui zeromq gxx_linux-64 gxx_linux-64 mesa-libgl-devel-cos6-x86_64 qt
# on fedora or newer systems
conda create -n slsgui qt
conda create -n slsgui zeromq qt
# when using conda compilers, would also need libgl, but no need for it on fedora unless maybe using it with ROOT
@ -242,9 +246,6 @@ Build slsDetectorGui (Qt5)
cd slsDetectorPackage
./cmk.sh -cbgj9
.. note ::
For v7.x.x of slsDetectorPackage and older, refer :ref:`zeromq notes for dependencies for conda. <zeromq for different slsDetectorPackage versions>`
@ -257,7 +258,7 @@ is to use conda
.. code-block:: bash
conda create -n myenv python=3.12 sphinx sphinx_rtd_theme breathe doxygen numpy
conda create -n myenv python sphinx_rtd_theme breathe
.. code-block:: bash
@ -269,51 +270,3 @@ is to use conda
make docs # generate API docs and build Sphinx RST
make rst # rst only, saves time in case the API did not change
Pybind and Zeromq
^^^^^^^^^^^^^^^^^^^
.. _pybind for different slsDetectorPackage versions:
| **Pybind for Python**
| v8.0.0+:
| pybind11 (v2.11.0) is built
| * by default from tar file in repo (libs/pybind/v2.11.0.tar.gz)
| * or use advanced option SLS_FETCH_PYBIND11_FROM_GITHUB [`link <https://github.com/pybind/pybind11>`__].
|
| v7.x.x:
| pybind11 packaged into 'libs/pybind'. No longer a submodule. No need for "recursive" or "submodule update".
|
| Older versions:
| pybind11 is a submodule. Must be cloned using "recursive" and updated when switching between versions using the following commands.
.. code-block:: bash
# Note: Only for v6.x.x versions and older
# clone using recursive to get pybind11 submodule
git clone --recursive https://github.com/slsdetectorgroup/slsDetectorPackage.git
# update submodule when switching between releases
cd slsDetectorPackage
git submodule update --init
.. _zeromq for different slsDetectorPackage versions:
| **Zeromq**
| v8.0.0+:
| zeromq (v4.3.4) is built
| * by default from tar file in repo (libs/libzmq/libzmq-4.3.4.tar.gz)
| * or use advanced option SLS_FETCH_ZMQ_FROM_GITHUB [`link <https://github.com/zeromq/libzmq.git>`__].
|
| v7.x.x and older:
| zeromq must be installed and one can hint its location using
| * cmake option:'-DZeroMQ_HINT=/usr/lib64' or
| * option '-q' in cmk.sh script: : ./cmk.sh -cbj5 -q /usr/lib64
| * 'zeromq' dependency added when installing using conda

View File

@ -109,14 +109,12 @@ For Multiple Modules
# connects to mulitple modules
hostname bchipxxx+bchipyyy+
# tcp port increases for each module (multi detector command)
rx_tcpport 2012
# connects to receivers at ports 2012 and 2014
rx_hostname mpc1922
rx_hostname mpc1922:2012+mpc1922:2013+
# increasing udp ports (multi detector command)
udp_dstport 50012
# sets differernt destination udp ports
0:udp_dstport 50012
1:udp_dstport 50014
# source udp ips must be same subnet at destintaion udp ips
0:udp_srcip 192.168.1.112

View File

@ -1,5 +1,3 @@
.. _Result Class:
Result
==============================================

View File

@ -52,13 +52,8 @@ Client Commands
# multi modules with custom ports
rx_hostname xxx:1955+xxx:1956+
# multi modules using increasing tcp ports when using multi detector command
rx_tcpport 1955
rx_hostname xxx
# or specify multi modules with custom ports on same rxr pc
# multi modules with custom ports on same rxr pc
0:rx_tcpport 1954
1:rx_tcpport 1955
2:rx_tcpport 1956

View File

@ -92,9 +92,6 @@ Common
sls_detector_put rx_arping 1
#. Only the slaves get no data
* Check trigger cabling and trigger configuration
* When you cannot stop Jungfrau slaves in sync mode, refer to :ref:`Cannot stop slaves<Jungfrau Troubleshooting Sync Slaves Cannot Stop>`.
.. _Receiver PC Tuning:
@ -424,20 +421,3 @@ Cannot get multi module data
* Comment out this line in the config file: powerchip 1
* Powering on the chip increases the power consumption by a considerable amount. If commenting out this line aids in getting data (strange data due to powered off chip), then it could be the power supply current limit. Fix it (possibly to 8A current limit) and uncomment the powerchip line back in config file.
.. _Jungfrau Troubleshooting Sync Slaves Cannot Stop:
Cannot stop slaves in sync mode
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#. If cabling is accessible, ensure termination board and flatband cable between the masters and the slaves are connnected properly. Then try to stop.
#. If cabling is inaccessible, unsync first so that the slaves can get the stop directly from the client using the command. Then, don't use sync mode until the cabling is fixed.
.. code-block:: bash
# unsync, slaves command will fail as it is still in waiting state
sls_detector_put sync 0
# stop should now be successful as master does not determine the stop anymore
sls_detector_put stop

View File

@ -86,8 +86,7 @@ For a Single Module (With Options)
udp_dstport 50012
# source udp ips must be same subnet at destintaion udp ips
# takes the same ip as hostname
udp_srcip auto
udp_srcip 192.168.1.112
# destination udp ip picked up from rx_hostname (if auto)
udp_dstip auto
@ -102,14 +101,12 @@ For Multiple Modules
virtual 2 1912
# or hostname localhost:1912+localhost:1914+
# increasing receiver tcp ports (multi detector command)
rx_tcpport 2012
# connects to receivers at ports 2012 and 2014
rx_hostname mpc1922:2012+mpc1922:2013+
# connects to reciever at port 2012 and 2013
rx_hostname mpc1922
# sets increasing destination udp ports
udp_dstport 50012
# sets differernt destination udp ports
0:udp_dstport 50012
1:udp_dstport 50014
# source udp ips must be same subnet at destintaion udp ips
0:udp_srcip 192.168.1.112

View File

@ -4,33 +4,27 @@ detsize 1024 512
# detector hostname for controls
hostname beb059+beb058+
# increasing receiver tcp port (multi detector command)
rx_tcpport 1991
# 1Gb receiver pc hostname to configure receiver
rx_hostname x12sa-vcons
# or 1Gb receiver pc hostname with tcp port to configure receiver
#rx_hostname x12sa-vcons:1991+x12sa-vcons:1992
# increasing udp destination ports for all half modules
udp_dstport 50011
# 1Gb receiver pc hostname with tcp port to configure receiver
rx_hostname x12sa-vcons:1991+x12sa-vcons:1992
# udp port first quadrant, first halfmodule
#0:udp_dstport 50011
0:udp_dstport 50011
# udp port second quadrant, first halfmodule
#0:udp_dstport2 50012
# udp port first quadrant, second halfmodule
#1:udp_dstport 50013
# udp port second quadrant, second halfmodule
#1:udp_dstport2 50014
0:udp_dstport2 50012
# udp IP of the receiver over 10Gb
0:udp_dstip 10.0.30.210
# first half module 10 Gb IP (same subnet as 0:udp_dstip)
0:udp_srcip 10.0.30.100
# udp port first quadrant, second halfmodule
1:udp_dstport 50013
# udp port second quadrant, second halfmodule
1:udp_dstport2 50014
# udp IP of the receiver over 10Gb,
1:udp_dstip 10.0.40.210

View File

@ -4,23 +4,18 @@ detsize 1024 512
# detector hostname for controls
hostname beb059+beb058+
# increasing receiver tcp port (multi detector command)
rx_tcpport 1991
# 1Gb receiver pc hostname to configure receiver
rx_hostname x12sa-vcons
# increasing udp destination ports for all half modules
udp_dstport 50011
# 1Gb receiver pc hostname with tcp port to configure receiver
rx_hostname x12sa-vcons:1991+x12sa-vcons:1992
# udp port first quadrant, first halfmodule
#0:udp_dstport 50011
0:udp_dstport 50011
#udp port second quadrant, first halfmodule
#0:udp_dstport2 50012
0:udp_dstport2 50012
# udp port first quadrant, second halfmodule
#1:udp_dstport 50013
1:udp_dstport 50013
# udp port second quadrant, second halfmodule
#1:udp_dstport2 50014
1:udp_dstport2 50014
# output directory
fpath /sls/X12SA/data/x12saop/Data10/Eiger0.5M

View File

@ -4,18 +4,14 @@ detsize 1024 1024
# detector hostname
hostname bchip048+bchip052+
# increasing receiver ports 1954 and 1955 (multi detector command)
rx_tcpport 1954
# 1Gb receiver pc hostname
rx_hostname pcmoench01
# 1Gb receiver pc hostname (default tcpport: 1954)
rx_hostname pcmoench01:1954+pcmoench01:1955+
# increasing udp ports 50004 and 50005 (multi detector command)
udp_dstport 50004
# or custom udp destination port (receiver) for 1st module
#0:udp_dstport 50014
# udp configurations for 1st module
# udp destination port (receiver)
0:udp_dstport 50004
# udp destination ip (receiver)
0:udp_dstip 10.1.1.100
@ -23,11 +19,17 @@ udp_dstport 50004
# udp source ip (same subnet as 0:udp_dstip)
0:udp_srcip 10.1.1.10
# udp configurations for 2nd module
# udp destination port (receiver)
1:udp_dstport 50005
# udp destination ip (receiver)
1:udp_dstip 10.1.2.100
1:udp_dstip 10.1.1.100
# udp source ip (same subnet as 1:udp_dstip)
1:udp_srcip 10.1.2.11
1:udp_srcip 10.1.1.11
@ -43,5 +45,5 @@ timing trigger
# output file directory
fpath /external_pool/jungfrau_data/softwaretest
# disable file writing (default)
# disable file writing
fwrite 0

View File

@ -2,8 +2,10 @@
hostname localhost:1900+localhost:1902+
# udp destination ports
udp_dstport 50000
udp_dstport2 50001
0:udp_dstport 50000
0:udp_dstport2 50001
1:udp_dstport 50002
1:udp_dstport2 50003
# receiver hostname
rx_hostname mpc1922:2000+mpc1922:2001+

View File

@ -5,26 +5,24 @@ detsize 2048 1024
virtual 4 1952
# udp destination ports
udp_dstport 50001
#0:udp_dstport2 50001
#0:udp_dstport2 50002
#1:udp_dstport 50003
#1:udp_dstport2 50004
#2:udp_dstport 50005
#2:udp_dstport2 50006
#3:udp_dstport 50007
#3:udp_dstport2 50008
0:udp_dstport2 50001
0:udp_dstport2 50002
1:udp_dstport 50003
1:udp_dstport2 50004
2:udp_dstport 50005
2:udp_dstport2 50006
3:udp_dstport 50007
3:udp_dstport2 50008
# udp source ip (same subnet as udp_dstip)
udp_srcip 192.168.1.100
udp_srcip2 192.168.1.100
# receiver hostname and tcpports
rx_tcpport 1970
#0:rx_tcpport 1970
#1:rx_tcpport 1971
#2:rx_tcpport 1972
#3:rx_tcpport 1973
0:rx_tcpport 1970
1:rx_tcpport 1971
2:rx_tcpport 1972
3:rx_tcpport 1973
rx_hostname mpc1922
# udp destination ip from rx_hostname

View File

@ -11,7 +11,6 @@ pybind11_add_module(_slsdet
src/current.cpp
src/duration.cpp
src/DurationWrapper.cpp
src/pedestal.cpp
)
target_link_libraries(_slsdet PUBLIC
@ -20,7 +19,7 @@ target_link_libraries(_slsdet PUBLIC
set_target_properties(_slsdet PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin/slsdet
)
#Copy Python code
@ -28,7 +27,8 @@ set( PYTHON_FILES
slsdet/__init__.py
slsdet/adcs.py
slsdet/dacs.py
slsdet/powers.py
slsdet/voltages.py
slsdet/slowadcs.py
slsdet/decorators.py
slsdet/detector_property.py
slsdet/detector.py
@ -49,6 +49,7 @@ set( PYTHON_FILES
slsdet/temperature.py
slsdet/lookup.py
slsdet/utils.py
setup.py
)
@ -58,7 +59,6 @@ foreach(FILE ${PYTHON_FILES})
endforeach(FILE ${PYTHON_FILES})
configure_file( scripts/basic.py
${CMAKE_BINARY_DIR}/basic.py
)

View File

@ -1,12 +0,0 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
from slsdet import Detector, pedestalParameters
p = pedestalParameters()
p.frames = 10
p.loops= 20
d = Detector()
d.pedestalmode = p

View File

@ -7,50 +7,16 @@ Build upon the pybind11 example found here: https://github.com/pybind/python_exa
import os
import sys
from pathlib import Path
# sys.path.append('../libs/pybind')
from setuptools import setup, find_packages
from pybind11.setup_helpers import Pybind11Extension, build_ext
__version__ = os.environ.get('GIT_DESCRIBE_TAG', 'developer')
def get_conda_path():
"""
Keep this a function if we need some fancier logic later
"""
print('Prefix: ', os.environ['CONDA_PREFIX'])
return os.environ['CONDA_PREFIX']
#TODO migrate to CMake build or fetch files from cmake?
ext_modules = [
Pybind11Extension(
'_slsdet',
['src/main.cpp',
'src/enums.cpp',
'src/current.cpp',
'src/detector.cpp',
'src/network.cpp',
'src/pattern.cpp',
'src/scan.cpp',
'src/duration.cpp',
'src/DurationWrapper.cpp',
'src/pedestal.cpp',
]
,
include_dirs=[
os.path.join(get_conda_path(), 'include'),
],
libraries=['SlsDetector', 'SlsSupport', 'SlsReceiver'],
library_dirs=[
os.path.join(get_conda_path(), 'lib'),
],
language='c++'
),
]
setup(
name='slsdet',
version=__version__,
@ -60,7 +26,7 @@ setup(
description='Detector API for SLS Detector Group detectors',
long_description='',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
ext_modules=ext_modules,
cmdclass={"build_ext": build_ext},
package_data={"":["*.so"]},
include_package_data=True,
zip_safe=False,
)

View File

@ -4,7 +4,8 @@
from .eiger import Eiger
from .ctb import Ctb
from .dacs import DetectorDacs, Dac
from .powers import DetectorPowers, Power
from .voltages import DetectorVoltages, Voltage
from .slowadcs import DetectorSlowAdcs, SlowAdc
from .detector import Detector
from .jungfrau import Jungfrau
from .mythen3 import Mythen3
@ -14,7 +15,7 @@ from .moench import Moench
from .pattern import Pattern, patternParameters
from .gaincaps import Mythen3GainCapsWrapper
import _slsdet
from . import _slsdet
xy = _slsdet.xy
defs = _slsdet.slsDetectorDefs
@ -26,5 +27,4 @@ IpAddr = _slsdet.IpAddr
MacAddr = _slsdet.MacAddr
scanParameters = _slsdet.scanParameters
currentSrcParameters = _slsdet.currentSrcParameters
DurationWrapper = _slsdet.DurationWrapper
pedestalParameters = _slsdet.pedestalParameters
DurationWrapper = _slsdet.DurationWrapper

View File

@ -3,8 +3,9 @@
from .detector import Detector, freeze
from .utils import element_if_equal
from .dacs import DetectorDacs, NamedDacs
from .powers import DetectorPowers, NamedPowers
import _slsdet
from .voltages import DetectorVoltages, NamedVoltages
from .slowadcs import DetectorSlowAdcs, NamedSlowAdcs
from . import _slsdet
dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty
@ -16,12 +17,17 @@ class Ctb(Detector):
super().__init__(id)
self._frozen = False
self._dacs = NamedDacs(self)
self._powers = NamedPowers(self)
self._voltages = NamedVoltages(self)
self._slowadcs = NamedSlowAdcs(self)
@property
def dacs(self):
return self._dacs
@property
def powers(self):
return self._powers
def voltages(self):
return self._voltages
@property
def slowadcs(self):
return self._slowadcs

View File

@ -3,7 +3,7 @@
from .detector_property import DetectorProperty
from functools import partial
import numpy as np
import _slsdet
from . import _slsdet
from .detector import freeze
dacIndex = _slsdet.slsDetectorDefs.dacIndex
class Dac(DetectorProperty):

View File

@ -1,8 +1,8 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
from _slsdet import CppDetectorApi
from _slsdet import slsDetectorDefs
from _slsdet import IpAddr, MacAddr
from ._slsdet import CppDetectorApi
from ._slsdet import slsDetectorDefs
from ._slsdet import IpAddr, MacAddr
runStatus = slsDetectorDefs.runStatus
timingMode = slsDetectorDefs.timingMode
@ -15,7 +15,7 @@ defs = slsDetectorDefs
from .utils import element_if_equal, all_equal, get_set_bits, list_to_bitmask
from .utils import Geometry, to_geo, element, reduce_time, is_iterable, hostname_list
from _slsdet import xy
from ._slsdet import xy
from .gaincaps import Mythen3GainCapsWrapper
from . import utils as ut
from .proxy import JsonProxy, SlowAdcProxy, ClkDivProxy, MaxPhaseProxy, ClkFreqProxy, PatLoopProxy, PatNLoopProxy, PatWaitProxy, PatWaitTimeProxy
@ -182,7 +182,6 @@ class Detector(CppDetectorApi):
@port.setter
def port(self, value):
ut.validate_port(value)
ut.set_using_dict(self.setControlPort, value)
@property
@ -198,7 +197,6 @@ class Detector(CppDetectorApi):
@stopport.setter
def stopport(self, args):
ut.validate_port(args)
ut.set_using_dict(self.setStopPort, args)
@ -360,8 +358,7 @@ class Detector(CppDetectorApi):
@property
def settings(self):
"""
Detector settings.
Enum: detectorSettings
Detector settings. Enum: detectorSettings
Note
-----
@ -401,9 +398,6 @@ class Detector(CppDetectorApi):
def framesl(self):
"""
[Gotthard][Jungfrau][Moench][Mythen3][Gotthard2][CTB] Number of frames left in acquisition.\n
Note
----
[Gotthard2] only in continuous auto mode.
:setter: Not Implemented
@ -479,8 +473,7 @@ class Detector(CppDetectorApi):
@element
def gaincaps(self):
"""
[Mythen3] Gain caps.
Enum: M3_GainCaps
[Mythen3] Gain caps. Enum: M3_GainCaps \n
Note
----
@ -578,6 +571,8 @@ class Detector(CppDetectorApi):
"""
Period between frames, accepts either a value in seconds or datetime.timedelta
Note
-----
:getter: always returns in seconds. To get in DurationWrapper, use getPeriod
Example
@ -644,6 +639,9 @@ class Detector(CppDetectorApi):
"""
[Gotthard][Jungfrau][Moench][CTB][Mythen3][Gotthard2] Delay after trigger, accepts either a value in seconds, DurationWrapper or datetime.timedelta
Note
-----
:getter: always returns in seconds. To get in DurationWrapper, use getDelayAfterTrigger
Example
@ -868,7 +866,6 @@ class Detector(CppDetectorApi):
@rx_tcpport.setter
def rx_tcpport(self, port):
ut.validate_port(port)
ut.set_using_dict(self.setRxPort, port)
@property
@ -895,8 +892,7 @@ class Detector(CppDetectorApi):
@element
def rx_discardpolicy(self):
"""
Frame discard policy of receiver.
Enum: frameDiscardPolicy
Frame discard policy of receiver. Enum: frameDiscardPolicy
Note
-----
@ -970,8 +966,7 @@ class Detector(CppDetectorApi):
@property
@element
def fformat(self):
""" File format of data file in receiver.
Enum: fileFormat
""" File format of data file in receiver. Enum: fileFormat
Note
-----
@ -1150,14 +1145,11 @@ class Detector(CppDetectorApi):
@rx_zmqport.setter
def rx_zmqport(self, port):
if isinstance(port, int):
ut.validate_port(port)
self.setRxZmqPort(port, -1)
elif isinstance(port, dict):
ut.validate_port(port)
ut.set_using_dict(self.setRxZmqPort, port)
elif is_iterable(port):
for i, p in enumerate(port):
ut.validate_port(p)
self.setRxZmqPort(p, i)
else:
raise ValueError("Unknown argument type")
@ -1187,14 +1179,11 @@ class Detector(CppDetectorApi):
@zmqport.setter
def zmqport(self, port):
if isinstance(port, int):
ut.validate_port(port)
self.setClientZmqPort(port, -1)
elif isinstance(port, dict):
ut.validate_port(port)
ut.set_using_dict(self.setClientZmqPort, port)
elif is_iterable(port):
for i, p in enumerate(port):
ut.validate_port(p)
self.setClientZmqPort(p, i)
else:
raise ValueError("Unknown argument type")
@ -1504,7 +1493,6 @@ class Detector(CppDetectorApi):
@udp_dstport.setter
def udp_dstport(self, port):
ut.validate_port(port)
ut.set_using_dict(self.setDestinationUDPPort, port)
@property
@ -1526,7 +1514,6 @@ class Detector(CppDetectorApi):
@udp_dstport2.setter
def udp_dstport2(self, port):
ut.validate_port(port)
ut.set_using_dict(self.setDestinationUDPPort2, port)
@property
@ -1567,8 +1554,7 @@ class Detector(CppDetectorApi):
@property
@element
def status(self):
"""Gets detector status.
Enum: runStatus
"""Gets detector status. Enum: runStatus
Note
-----
@ -1582,8 +1568,7 @@ class Detector(CppDetectorApi):
@property
@element
def rx_status(self):
"""Gets receiver listener status.
Enum: runStatus
"""Gets receiver listener status. Enum: runStatus
Note
-----
@ -1677,11 +1662,6 @@ class Detector(CppDetectorApi):
def sync(self):
"""
[Jungfrau][Moench] Enables or disables synchronization between modules.
Note
----
Sync mode requires at least one master configured. Also requires flatband cabling between master and slave with termination board.
"""
return self.getSynchronization()
@ -1812,7 +1792,6 @@ class Detector(CppDetectorApi):
def daclist(self):
"""
List of enums/names for every dac for this detector
:setter: Only implemented for Chiptestboard
"""
@ -1825,7 +1804,9 @@ class Detector(CppDetectorApi):
@property
def adclist(self):
"""
[Chiptestboard] List of names for every adc for this board. 32 adcs
List of names for every adc for this board. 32 adcs
:setter: Only implemented for Chiptestboard
"""
return self.getAdcNames()
@ -1836,7 +1817,9 @@ class Detector(CppDetectorApi):
@property
def signallist(self):
"""
[Chiptestboard] List of names for every io signal for this board. 64 signals
List of names for every io signal for this board. 64 signals
:setter: Only implemented for Chiptestboard
"""
return self.getSignalNames()
@ -1845,21 +1828,23 @@ class Detector(CppDetectorApi):
self.setSignalNames(value)
@property
def powerlist(self):
def voltagelist(self):
"""
[Chiptestboard] List of names for every power for this board. 5 power supply
List of names for every voltage for this board. 5 voltage supply
:setter: Only implemented for Chiptestboard
"""
return self.getPowerNames()
return self.getVoltageNames()
@powerlist.setter
def powerlist(self, value):
self.setPowerNames(value)
@voltagelist.setter
def voltagelist(self, value):
self.setVoltageNames(value)
@property
def slowadclist(self):
"""
[Chiptestboard] List of names for every slowadc for this board. 8 slowadc
List of names for every slowadc for this board. 8 slowadc
:setter: Only implemented for Chiptestboard
"""
return self.getSlowADCNames()
@ -1877,16 +1862,16 @@ class Detector(CppDetectorApi):
}
@property
def powervalues(self):
"""[Chiptestboard] Gets the power values for every power for this detector."""
def voltagevalues(self):
"""Gets the voltage values for every voltage for this detector."""
return {
power.name.lower(): element_if_equal(np.array(self.getPower(power)))
for power in self.getPowerList()
voltage.name.lower(): element_if_equal(np.array(self.getVoltage(voltage)))
for voltage in self.getVoltageList()
}
@property
def slowadcvalues(self):
"""[Chiptestboard] Gets the slow adc values for every slow adc for this detector."""
"""Gets the slow adc values for every slow adc for this detector."""
return {
slowadc.name.lower(): element_if_equal(np.array(self.getSlowADC(slowadc)))
for slowadc in self.getSlowADCList()
@ -2041,7 +2026,6 @@ class Detector(CppDetectorApi):
@virtual.setter
def virtual(self, args):
n_detectors, starting_port = args
ut.validate_port(starting_port)
self.setVirtualDetectorServers(n_detectors, starting_port)
@ -2060,7 +2044,8 @@ class Detector(CppDetectorApi):
-----
To set default rate correction from trimbit file, use setDefaultRateCorrection
Known Issue:
Known Issue
------------
:getter: Always give 0 due to the microseconds precision.
:setter: Use scientific notation to set custom rate correction, since timedelta resolution is 1 microseconds. \n
@ -2084,8 +2069,7 @@ class Detector(CppDetectorApi):
@element
def readoutspeed(self):
"""
[Eiger][Jungfrau|Gotthard2] Readout speed of chip.
Enum: speedLevel
[Eiger][Jungfrau|Gotthard2] Readout speed of chip. Enum: speedLevel
Note
-----
@ -2174,8 +2158,7 @@ class Detector(CppDetectorApi):
@element
def timing(self):
"""
Set Timing Mode of detector.
Enum: timingMode
Set Timing Mode of detector. Enum: timingMode
Note
-----
@ -2235,11 +2218,13 @@ class Detector(CppDetectorApi):
@property
@element
def type(self):
""" Returns detector type.
Enum: detectorType
[EIGER, JUNGFRAU, GOTTHARD, MOENCH, MYTHEN3, GOTTHARD2, CHIPTESTBOARD]
""" Returns detector type. Enum: detectorType
Note
----
:setter: Not implemented
Values: EIGER, JUNGFRAU, GOTTHARD, MOENCH, MYTHEN3, GOTTHARD2, CHIPTESTBOARD
"""
return self.getDetectorType()
@ -2500,6 +2485,9 @@ class Detector(CppDetectorApi):
"""
[Eiger] Measured sub frame period between last sub frame and previous one.
Note
-----
:setter: Not implemented
"""
return ut.reduce_time(self.getMeasuredSubFramePeriod())
@ -2777,8 +2765,7 @@ class Detector(CppDetectorApi):
@property
def gainmode(self):
"""
[Jungfrau] Detector gain mode.
Enum: gainMode
[Jungfrau] Detector gain mode. Enum: gainMode
Note
-----
@ -2867,32 +2854,15 @@ class Detector(CppDetectorApi):
@filtercells.setter
def filtercells(self, value):
ut.set_using_dict(self.setNumberOfFilterCells, value)
@property
@element
def pedestalmode(self):
"""
[Jungfrau] Enables or disables pedestal mode. Pass in a pedestalParameters object
see python/examples/use_pedestalmode.py
Note
----
The number of frames or triggers is overwritten by #pedestal_frames x pedestal_loops x 2. \n
In auto timing mode or in trigger mode with #frames > 1, #frames is overwritten and #triggers = 1, else #triggers is overwritten and #frames = 1. \n
One cannot set #frames, #triggers or timing mode in pedestal mode (exception thrown).\n
Disabling pedestal mode will set back the normal mode values of #frames and #triggers."
"""
return self.getPedestalMode()
@pedestalmode.setter
def pedestalmode(self, value):
ut.set_using_dict(self.setPedestalMode, value)
@property
def maxclkphaseshift(self):
"""
[Gotthard2][Mythen3] Absolute maximum Phase shift of clocks.
[Gotthard2][Mythen3] Absolute maximum Phase shift of clocks.
Note
----
:setter: Not Implemented
Example
@ -2910,8 +2880,7 @@ class Detector(CppDetectorApi):
@element
def timingsource(self):
"""
[Gotthard2] Timing source.
Enum: timingSourceType
[Gotthard2] Timing source. Enum: timingSourceType
Note
-----
@ -2955,8 +2924,7 @@ class Detector(CppDetectorApi):
@property
@element
def burstmode(self):
"""[Gotthard2] Burst mode of detector.
Enum: burstMode
"""[Gotthard2] Burst mode of detector. Enum: burstMode
Note
----
@ -2974,6 +2942,9 @@ class Detector(CppDetectorApi):
"""
[Gotthard2] Period between 2 bursts. Only in burst mode and auto timing mode.
Note
-----
:getter: always returns in seconds. To get in DurationWrapper, use getBurstPeriod
:setter: Not Implemented
@ -3096,8 +3067,7 @@ class Detector(CppDetectorApi):
@property
def vetoalg(self):
"""[Gotthard2] Algorithm used for veto.
Enum: vetoAlgorithm, streamingInterface
"""[Gotthard2] Algorithm used for veto. Enum: vetoAlgorithm, streamingInterface
Note
----
@ -3271,8 +3241,7 @@ class Detector(CppDetectorApi):
@element
def romode(self):
"""
[CTB] Readout mode of detector.
Enum: readoutMode
[CTB] Readout mode of detector. Enum: readoutMode
Note
------
@ -3378,6 +3347,9 @@ class Detector(CppDetectorApi):
def maxdbitphaseshift(self):
"""[CTB][Jungfrau] Absolute maximum Phase shift of of the clock to latch digital bits.
Note
-----
:setter: Not Implemented
"""
return self.getMaxDBITPhaseShift()
@ -3422,6 +3394,9 @@ class Detector(CppDetectorApi):
def maxadcphaseshift(self):
"""[Jungfrau][Moench][CTB] Absolute maximum Phase shift of ADC clock.
Note
-----
:setter: Not Implemented
"""
return self.getMaxADCPhaseShift()
@ -3471,6 +3446,9 @@ class Detector(CppDetectorApi):
"""
[Ctb] Sync clock in MHz.
Note
-----
:setter: Not implemented
"""
return self.getSYNCClock()
@ -3478,7 +3456,10 @@ class Detector(CppDetectorApi):
@property
def pattern(self):
"""[Mythen3][Ctb] Loads ASCII pattern file directly to server (instead of executing line by line).
Note
----
:getter: Not Implemented
Example
@ -3833,80 +3814,83 @@ class Detector(CppDetectorApi):
@property
@element
def v_a(self):
"""[Ctb] Power supply a in mV."""
return self.getPower(dacIndex.V_POWER_A)
"""[Ctb] Voltage supply a in mV."""
return self.getVoltage(dacIndex.V_POWER_A)
@v_a.setter
def v_a(self, value):
value = ut.merge_args(dacIndex.V_POWER_A, value)
ut.set_using_dict(self.setPower, *value)
ut.set_using_dict(self.setVoltage, *value)
@property
@element
def v_b(self):
"""[Ctb] Power supply b in mV."""
return self.getPower(dacIndex.V_POWER_B)
"""[Ctb] Voltage supply b in mV."""
return self.getVoltage(dacIndex.V_POWER_B)
@v_b.setter
def v_b(self, value):
value = ut.merge_args(dacIndex.V_POWER_B, value)
ut.set_using_dict(self.setPower, *value)
ut.set_using_dict(self.setVoltage, *value)
@property
@element
def v_c(self):
"""[Ctb] Power supply c in mV."""
return self.getPower(dacIndex.V_POWER_C)
"""[Ctb] Voltage supply c in mV."""
return self.getVoltage(dacIndex.V_POWER_C)
@v_c.setter
def v_c(self, value):
value = ut.merge_args(dacIndex.V_POWER_C, value)
ut.set_using_dict(self.setPower, *value)
ut.set_using_dict(self.setVoltage, *value)
@property
@element
def v_d(self):
"""[Ctb] Power supply d in mV."""
return self.getPower(dacIndex.V_POWER_D)
"""[Ctb] Voltage supply d in mV."""
return self.getVoltage(dacIndex.V_POWER_D)
@v_d.setter
def v_d(self, value):
value = ut.merge_args(dacIndex.V_POWER_D, value)
ut.set_using_dict(self.setPower, *value)
ut.set_using_dict(self.setVoltage, *value)
@property
@element
def v_io(self):
"""[Ctb] Power supply io in mV. Minimum 1200 mV.
"""[Ctb] Voltage supply io in mV. Minimum 1200 mV.
Note
----
Must be the first power regulator to be set after fpga reset (on-board detector server start up).
"""
return self.getPower(dacIndex.V_POWER_IO)
return self.getVoltage(dacIndex.V_POWER_IO)
@v_io.setter
def v_io(self, value):
value = ut.merge_args(dacIndex.V_POWER_IO, value)
ut.set_using_dict(self.setPower, *value)
ut.set_using_dict(self.setVoltage, *value)
@property
@element
def v_limit(self):
"""[Ctb] Soft limit for power supplies (ctb only) and DACS in mV."""
return self.getPower(dacIndex.V_LIMIT)
return self.getVoltage(dacIndex.V_LIMIT)
@v_limit.setter
def v_limit(self, value):
value = ut.merge_args(dacIndex.V_LIMIT, value)
ut.set_using_dict(self.setPower, *value)
ut.set_using_dict(self.setVoltage, *value)
@property
@element
def im_a(self):
"""[Ctb] Measured current of power supply a in mA.
Note
-----
:setter: Not implemented
"""
return self.getMeasuredCurrent(dacIndex.I_POWER_A)
@ -3916,6 +3900,9 @@ class Detector(CppDetectorApi):
def im_b(self):
"""[Ctb] Measured current of power supply b in mA.
Note
-----
:setter: Not implemented
"""
return self.getMeasuredCurrent(dacIndex.I_POWER_B)
@ -3925,6 +3912,9 @@ class Detector(CppDetectorApi):
def im_c(self):
"""[Ctb] Measured current of power supply c in mA.
Note
-----
:setter: Not implemented
"""
return self.getMeasuredCurrent(dacIndex.I_POWER_C)
@ -3934,6 +3924,9 @@ class Detector(CppDetectorApi):
def im_d(self):
"""[Ctb] Measured current of power supply d in mA.
Note
-----
:setter: Not implemented
"""
return self.getMeasuredCurrent(dacIndex.I_POWER_D)
@ -3943,6 +3936,9 @@ class Detector(CppDetectorApi):
def im_io(self):
"""[Ctb] Measured current of power supply io in mA.
Note
-----
:setter: Not implemented
"""
return self.getMeasuredCurrent(dacIndex.I_POWER_IO)
@ -3992,6 +3988,9 @@ class Detector(CppDetectorApi):
def exptimel(self):
"""[Gotthard] Exposure time left for current frame.
Note
-----
:getter: always returns in seconds. To get in DurationWrapper, use getExptimeLeft
:setter: Not Implemented
@ -4026,6 +4025,9 @@ class Detector(CppDetectorApi):
"""
[Gotthard2][Mythen3] Frequency of clock in Hz.
Note
----
:setter: Not implemented. Use clkdiv to set frequency
Example
@ -4045,9 +4047,7 @@ class Detector(CppDetectorApi):
@property
@element
def polarity(self):
"""[Mythen3] Set positive or negative polarity.
Enum: polarity
"""
"""[Mythen3] Set positive or negative polarity. Enum: polarity"""
return self.getPolarity()
@polarity.setter

View File

@ -11,7 +11,7 @@ Created on Wed Dec 6 11:51:18 2017
from .detector import Detector
from .temperature import Temperature, DetectorTemperature
from .dacs import DetectorDacs
import _slsdet
from . import _slsdet
dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty

View File

@ -15,8 +15,9 @@ if dt === detectorType.EIGER:
"""
import _slsdet
for name, cls in _slsdet.slsDetectorDefs.__dict__.items():
from . import _slsdet
import slsdet._slsdet
for name, cls in slsdet._slsdet.slsDetectorDefs.__dict__.items():
if isinstance(cls, type):
exec(f'{name} = {cls.__module__}.{cls.__qualname__}')

View File

@ -1,6 +1,6 @@
import _slsdet
from . import _slsdet
gc = _slsdet.slsDetectorDefs.M3_GainCaps

View File

@ -9,7 +9,7 @@ This file contains the specialization for the Moench detector
from .detector import Detector, freeze
from .dacs import DetectorDacs
import _slsdet
from . import _slsdet
dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty

View File

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

View File

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

View File

@ -9,7 +9,7 @@ This file contains the specialization for the Moench detector
from .detector import Detector, freeze
from .dacs import DetectorDacs
import _slsdet
from . import _slsdet
dacIndex = _slsdet.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty

View File

@ -11,7 +11,7 @@ from .detector import Detector, freeze
# from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs
import _slsdet
from . import _slsdet
dacIndex = _slsdet.slsDetectorDefs.dacIndex
gc_enums = _slsdet.slsDetectorDefs.M3_GainCaps
from .detector_property import DetectorProperty

View File

@ -1,8 +1,8 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
import _slsdet
from . import _slsdet
from _slsdet import Pattern
from ._slsdet import Pattern
class patternParameters(_slsdet.patternParameters):

View File

@ -1,195 +0,0 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
from .detector_property import DetectorProperty
from functools import partial
import numpy as np
import _slsdet
from .detector import freeze
dacIndex = _slsdet.slsDetectorDefs.dacIndex
class Power(DetectorProperty):
"""
This class represents a power on the Chip Test Board. One instance handles all
powers with the same name for a multi detector instance. (TODO: Not needed for CTB)
.. note ::
This class is used to build up DetectorPowers and is in general
not directly accessible to the user.
"""
def __init__(self, name, enum, default, detector):
super().__init__(partial(detector.getPower, enum),
lambda x, y : detector.setPower(enum, x, y),
detector.size,
name)
self.default = default
def __repr__(self):
"""String representation for a single power in all modules"""
powerstr = ''.join([f'{item:5d}' for item in self.get()])
return f'{self.__name__:15s}:{powerstr}'
class NamedPowers:
"""
New implementation of the detector powers.
"""
_frozen = False
_direct_access = ['_detector', '_current', '_powernames']
def __init__(self, detector):
self._detector = detector
self._current = 0
#only get the powernames if we have modules attached
if detector.size() == 0:
self._powernames = ["VA", "VB", "VC", "VD", "VIO"]
else:
self._powernames = [n.replace(" ", "") for n in detector.getPowerNames()]
# Populate the powers
for i,name in enumerate(self._powernames):
#name, enum, low, high, default, detector
k = dacIndex(i + int(dacIndex.V_POWER_A))
setattr(self, name, Power(name, k, 0, detector))
self._frozen = True
# def __getattr__(self, name):
# return self.__getattribute__('_' + name)
def __setattr__(self, name, value):
if not self._frozen:
#durning init we need to be able to set up the class
super().__setattr__(name, value)
else:
#Later we restrict us to manipulate powers and a few fields
if name in self._direct_access:
super().__setattr__(name, value)
elif name in self._powernames:
return self.__getattribute__(name).__setitem__(slice(None, None), value)
else:
raise AttributeError(f'Power not found: {name}')
def __next__(self):
if self._current >= len(self._powernames):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattribute__(self._powernames[self._current-1])
# return self.__getattr__(self._powernames[self._current-1])
def __iter__(self):
return self
def __repr__(self):
r_str = ['========== POWERS =========']
r_str += [repr(power) for power in self]
return '\n'.join(r_str)
def get_asarray(self):
"""
Read the powers into a numpy array with dimensions [npowers, nmodules]
"""
power_array = np.zeros((len(self._powernames), len(self._detector)))
for i, _d in enumerate(self):
power_array[i,:] = _d[:]
return power_array
def to_array(self):
return self.get_asarray()
def set_from_array(self, power_array):
"""
Set the power from an numpy array with power values. [npowers, nmodules]
"""
power_array = power_array.astype(np.int)
for i, _d in enumerate(self):
_d[:] = power_array[i]
def from_array(self, power_array):
self.set_from_array(power_array)
class DetectorPowers:
_powers = []
_powernames = [_d[0] for _d in _powers]
_allowed_attr = ['_detector', '_current']
_frozen = False
def __init__(self, detector):
# We need to at least initially know which detector we are connected to
self._detector = detector
# Index to support iteration
self._current = 0
# Name the attributes?
for _d in self._powers:
setattr(self, '_'+_d[0], Power(*_d, detector))
self._frozen = True
def __getattr__(self, name):
return self.__getattribute__('_' + name)
@property
def powernames(self):
return [_d[0] for _d in _powers]
def __setattr__(self, name, value):
if name in self._powernames:
return self.__getattribute__('_' + name).__setitem__(slice(None, None), value)
else:
if self._frozen == True and name not in self._allowed_attr:
raise AttributeError(f'Power not found: {name}')
super().__setattr__(name, value)
def __next__(self):
if self._current >= len(self._powers):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattr__(self._powernames[self._current-1])
def __iter__(self):
return self
def __repr__(self):
r_str = ['========== POWERS =========']
r_str += [repr(power) for power in self]
return '\n'.join(r_str)
def get_asarray(self):
"""
Read the powers into a numpy array with dimensions [npowers, nmodules]
"""
power_array = np.zeros((len(self._powers), len(self._detector)))
for i, _d in enumerate(self):
power_array[i,:] = _d[:]
return power_array
def to_array(self):
return self.get_asarray()
def set_from_array(self, power_array):
"""
Set the powers from an numpy array with power values. [npowers, nmodules]
"""
power_array = power_array.astype(np.int)
for i, _d in enumerate(self):
_d[:] = power_array[i]
def from_array(self, power_array):
self.set_from_array(power_array)
def set_default(self):
"""
Set all powers to their default values
"""
for _d in self:
_d[:] = _d.default

View File

@ -3,7 +3,7 @@
from .utils import element_if_equal
from .enums import dacIndex
from .defines import M3_MAX_PATTERN_LEVELS, MAX_PATTERN_LEVELS
from _slsdet import slsDetectorDefs
from ._slsdet import slsDetectorDefs
detectorType = slsDetectorDefs.detectorType
@ -60,27 +60,18 @@ class SlowAdcProxy:
def __getitem__(self, key):
dac_index = dacIndex(int(dacIndex.SLOW_ADC0)+key)
return element_if_equal(self.det.getSlowADC(dac_index))/1000 #TODO! Multi module?
return element_if_equal(self.det.getSlowADC(dac_index))
def __repr__(self):
rstr = ''
for i,name in enumerate(self.det.getSlowADCNames()):
for i in range(8):
r = element_if_equal(self.__getitem__(i))
if isinstance(r, list):
rstr += ' '.join(f'{item/1000} mV' for item in r)
rstr += ' '.join(f'{item} uV' for item in r)
else:
rstr += f'[{i}] {name}: {r/1000} mV\n'
rstr += f'{i}: {r} uV\n'
return rstr.strip('\n')
def __getattr__(self, name):
if name in self.det.getSlowADCNames():
i = self.det.getSlowADCIndex(name)
return element_if_equal(self.det.getSlowADC(i))
else:
raise ValueError(f"Could not find slow adc with name: {name}")
class ClkDivProxy:
"""

195
python/slsdet/slowadcs.py Executable file
View File

@ -0,0 +1,195 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
from .detector_property import DetectorProperty
from functools import partial
import numpy as np
from . import _slsdet
from .detector import freeze
dacIndex = _slsdet.slsDetectorDefs.dacIndex
class SlowAdc(DetectorProperty):
"""
This class represents a slowadc on the Chip Test Board. One instance handles all
slowadcs with the same name for a multi detector instance. (TODO: Not needed for CTB)
.. note ::
This class is used to build up DetectorSlowAdcs and is in general
not directly accessible to the user.
"""
def __init__(self, name, enum, default, detector):
super().__init__(partial(detector.getVoltage, enum),
lambda x, y : detector.setVoltage(enum, x, y),
detector.size,
name)
self.default = default
def __repr__(self):
"""String representation for a single slowadc in all modules"""
slowadcstr = ''.join([f'{item:5d}' for item in self.get()])
return f'{self.__name__:15s}:{slowadcstr}'
class NamedSlowAdcs:
"""
New implementation of the detector slowadcs.
"""
_frozen = False
_direct_access = ['_detector', '_current', '_voltagenames']
def __init__(self, detector):
self._detector = detector
self._current = 0
#only get the voltagenames if we have modules attached
if detector.size() == 0:
self._voltagenames = ["VA", "VB", "VC", "VD", "VIO"]
else:
self._voltagenames = [n.replace(" ", "") for n in detector.getVoltageNames()]
# Populate the slowadcs
for i,name in enumerate(self._voltagenames):
#name, enum, low, high, default, detector
k = dacIndex(i + int(dacIndex.V_POWER_A))
setattr(self, name, SlowAdc(name, k, 0, detector))
self._frozen = True
# def __getattr__(self, name):
# return self.__getattribute__('_' + name)
def __setattr__(self, name, value):
if not self._frozen:
#durning init we need to be able to set up the class
super().__setattr__(name, value)
else:
#Later we restrict us to manipulate slowadcs and a few fields
if name in self._direct_access:
super().__setattr__(name, value)
elif name in self._voltagenames:
return self.__getattribute__(name).__setitem__(slice(None, None), value)
else:
raise AttributeError(f'SlowAdc not found: {name}')
def __next__(self):
if self._current >= len(self._voltagenames):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattribute__(self._voltagenames[self._current-1])
# return self.__getattr__(self._voltagenames[self._current-1])
def __iter__(self):
return self
def __repr__(self):
r_str = ['========== SLOW ADCS =========']
r_str += [repr(slowadc) for slowadc in self]
return '\n'.join(r_str)
def get_asarray(self):
"""
Read the slowadcs into a numpy array with dimensions [nslowadcs, nmodules]
"""
voltage_array = np.zeros((len(self._voltagenames), len(self._detector)))
for i, _d in enumerate(self):
voltage_array[i,:] = _d[:]
return voltage_array
def to_array(self):
return self.get_asarray()
def set_from_array(self, voltage_array):
"""
Set the slowadc from an numpy array with slowadc values. [nslowadcs, nmodules]
"""
voltage_array = voltage_array.astype(np.int)
for i, _d in enumerate(self):
_d[:] = voltage_array[i]
def from_array(self, voltage_array):
self.set_from_array(voltage_array)
class DetectorSlowAdcs:
_slowadcs = []
_voltagenames = [_d[0] for _d in _slowadcs]
_allowed_attr = ['_detector', '_current']
_frozen = False
def __init__(self, detector):
# We need to at least initially know which detector we are connected to
self._detector = detector
# Index to support iteration
self._current = 0
# Name the attributes?
for _d in self._slowadcs:
setattr(self, '_'+_d[0], SlowAdc(*_d, detector))
self._frozen = True
def __getattr__(self, name):
return self.__getattribute__('_' + name)
@property
def voltagenames(self):
return [_d[0] for _d in _slowadcs]
def __setattr__(self, name, value):
if name in self._voltagenames:
return self.__getattribute__('_' + name).__setitem__(slice(None, None), value)
else:
if self._frozen == True and name not in self._allowed_attr:
raise AttributeError(f'SlowAdc not found: {name}')
super().__setattr__(name, value)
def __next__(self):
if self._current >= len(self._slowadcs):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattr__(self._voltagenames[self._current-1])
def __iter__(self):
return self
def __repr__(self):
r_str = ['========== SLOW ADCS =========']
r_str += [repr(slowadc) for slowadc in self]
return '\n'.join(r_str)
def get_asarray(self):
"""
Read the slowadcs into a numpy array with dimensions [nslowadcs, nmodules]
"""
voltage_array = np.zeros((len(self._slowadcs), len(self._detector)))
for i, _d in enumerate(self):
voltage_array[i,:] = _d[:]
return voltage_array
def to_array(self):
return self.get_asarray()
def set_from_array(self, voltage_array):
"""
Set the slowadcs from an numpy array with slowadc values. [nslowadcs, nmodules]
"""
voltage_array = voltage_array.astype(np.int)
for i, _d in enumerate(self):
_d[:] = voltage_array[i]
def from_array(self, voltage_array):
self.set_from_array(voltage_array)
def set_default(self):
"""
Set all slowadcs to their default values
"""
for _d in self:
_d[:] = _d.default

View File

@ -6,7 +6,7 @@ but not directly used in controlling the detector
"""
from collections import namedtuple
import _slsdet #C++ lib
from . import _slsdet #C++ lib
import functools
import datetime as dt
import pathlib
@ -278,9 +278,3 @@ def hostname_list(args):
return hosts
else:
raise ValueError("hostname needs to be string or list of strings")
def validate_port(value):
if value <= 0 or value > 65535:
raise ValueError("port must be in range 1 - 65535")

195
python/slsdet/voltages.py Executable file
View File

@ -0,0 +1,195 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
from .detector_property import DetectorProperty
from functools import partial
import numpy as np
from . import _slsdet
from .detector import freeze
dacIndex = _slsdet.slsDetectorDefs.dacIndex
class Voltage(DetectorProperty):
"""
This class represents a voltage on the Chip Test Board. One instance handles all
voltages with the same name for a multi detector instance. (TODO: Not needed for CTB)
.. note ::
This class is used to build up DetectorVoltages and is in general
not directly accessible to the user.
"""
def __init__(self, name, enum, default, detector):
super().__init__(partial(detector.getVoltage, enum),
lambda x, y : detector.setVoltage(enum, x, y),
detector.size,
name)
self.default = default
def __repr__(self):
"""String representation for a single voltage in all modules"""
voltagestr = ''.join([f'{item:5d}' for item in self.get()])
return f'{self.__name__:15s}:{voltagestr}'
class NamedVoltages:
"""
New implementation of the detector voltages.
"""
_frozen = False
_direct_access = ['_detector', '_current', '_voltagenames']
def __init__(self, detector):
self._detector = detector
self._current = 0
#only get the voltagenames if we have modules attached
if detector.size() == 0:
self._voltagenames = ["VA", "VB", "VC", "VD", "VIO"]
else:
self._voltagenames = [n.replace(" ", "") for n in detector.getVoltageNames()]
# Populate the voltages
for i,name in enumerate(self._voltagenames):
#name, enum, low, high, default, detector
k = dacIndex(i + int(dacIndex.V_POWER_A))
setattr(self, name, Voltage(name, k, 0, detector))
self._frozen = True
# def __getattr__(self, name):
# return self.__getattribute__('_' + name)
def __setattr__(self, name, value):
if not self._frozen:
#durning init we need to be able to set up the class
super().__setattr__(name, value)
else:
#Later we restrict us to manipulate voltages and a few fields
if name in self._direct_access:
super().__setattr__(name, value)
elif name in self._voltagenames:
return self.__getattribute__(name).__setitem__(slice(None, None), value)
else:
raise AttributeError(f'Voltage not found: {name}')
def __next__(self):
if self._current >= len(self._voltagenames):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattribute__(self._voltagenames[self._current-1])
# return self.__getattr__(self._voltagenames[self._current-1])
def __iter__(self):
return self
def __repr__(self):
r_str = ['========== VOLTAGES =========']
r_str += [repr(voltage) for voltage in self]
return '\n'.join(r_str)
def get_asarray(self):
"""
Read the voltages into a numpy array with dimensions [nvoltages, nmodules]
"""
voltage_array = np.zeros((len(self._voltagenames), len(self._detector)))
for i, _d in enumerate(self):
voltage_array[i,:] = _d[:]
return voltage_array
def to_array(self):
return self.get_asarray()
def set_from_array(self, voltage_array):
"""
Set the voltage from an numpy array with voltage values. [nvoltages, nmodules]
"""
voltage_array = voltage_array.astype(np.int)
for i, _d in enumerate(self):
_d[:] = voltage_array[i]
def from_array(self, voltage_array):
self.set_from_array(voltage_array)
class DetectorVoltages:
_voltages = []
_voltagenames = [_d[0] for _d in _voltages]
_allowed_attr = ['_detector', '_current']
_frozen = False
def __init__(self, detector):
# We need to at least initially know which detector we are connected to
self._detector = detector
# Index to support iteration
self._current = 0
# Name the attributes?
for _d in self._voltages:
setattr(self, '_'+_d[0], Voltage(*_d, detector))
self._frozen = True
def __getattr__(self, name):
return self.__getattribute__('_' + name)
@property
def voltagenames(self):
return [_d[0] for _d in _voltages]
def __setattr__(self, name, value):
if name in self._voltagenames:
return self.__getattribute__('_' + name).__setitem__(slice(None, None), value)
else:
if self._frozen == True and name not in self._allowed_attr:
raise AttributeError(f'Voltage not found: {name}')
super().__setattr__(name, value)
def __next__(self):
if self._current >= len(self._voltages):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattr__(self._voltagenames[self._current-1])
def __iter__(self):
return self
def __repr__(self):
r_str = ['========== VOLTAGES =========']
r_str += [repr(voltage) for voltage in self]
return '\n'.join(r_str)
def get_asarray(self):
"""
Read the voltages into a numpy array with dimensions [nvoltages, nmodules]
"""
voltage_array = np.zeros((len(self._voltages), len(self._detector)))
for i, _d in enumerate(self):
voltage_array[i,:] = _d[:]
return voltage_array
def to_array(self):
return self.get_asarray()
def set_from_array(self, voltage_array):
"""
Set the voltages from an numpy array with voltage values. [nvoltages, nmodules]
"""
voltage_array = voltage_array.astype(np.int)
for i, _d in enumerate(self):
_d[:] = voltage_array[i]
def from_array(self, voltage_array):
self.set_from_array(voltage_array)
def set_default(self):
"""
Set all voltages to their default values
"""
for _d in self:
_d[:] = _d.default

View File

@ -48,7 +48,7 @@ void init_det(py::module &m) {
Detector::setHostname,
py::arg());
CppDetectorApi.def("setVirtualDetectorServers",
(void (Detector::*)(int, uint16_t)) &
(void (Detector::*)(int, int)) &
Detector::setVirtualDetectorServers,
py::arg(), py::arg());
CppDetectorApi.def("getShmId",
@ -751,19 +751,19 @@ void init_det(py::module &m) {
Detector::setDestinationUDPMAC2,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getDestinationUDPPort",
(Result<uint16_t>(Detector::*)(sls::Positions) const) &
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getDestinationUDPPort,
py::arg() = Positions{});
CppDetectorApi.def("setDestinationUDPPort",
(void (Detector::*)(uint16_t, int)) &
(void (Detector::*)(int, int)) &
Detector::setDestinationUDPPort,
py::arg(), py::arg() = -1);
CppDetectorApi.def("getDestinationUDPPort2",
(Result<uint16_t>(Detector::*)(sls::Positions) const) &
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getDestinationUDPPort2,
py::arg() = Positions{});
CppDetectorApi.def("setDestinationUDPPort2",
(void (Detector::*)(uint16_t, int)) &
(void (Detector::*)(int, int)) &
Detector::setDestinationUDPPort2,
py::arg(), py::arg() = -1);
CppDetectorApi.def("reconfigureUDPDestination",
@ -844,12 +844,12 @@ void init_det(py::module &m) {
Detector::setRxHostname,
py::arg());
CppDetectorApi.def("getRxPort",
(Result<uint16_t>(Detector::*)(sls::Positions) const) &
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getRxPort,
py::arg() = Positions{});
CppDetectorApi.def(
"setRxPort", (void (Detector::*)(uint16_t, int)) & Detector::setRxPort,
py::arg(), py::arg() = -1);
CppDetectorApi.def("setRxPort",
(void (Detector::*)(int, int)) & Detector::setRxPort,
py::arg(), py::arg() = -1);
CppDetectorApi.def("getRxFifoDepth",
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getRxFifoDepth,
@ -1032,12 +1032,11 @@ void init_det(py::module &m) {
Detector::setRxZmqStartingFrame,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getRxZmqPort",
(Result<uint16_t>(Detector::*)(sls::Positions) const) &
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getRxZmqPort,
py::arg() = Positions{});
CppDetectorApi.def("setRxZmqPort",
(void (Detector::*)(uint16_t, int)) &
Detector::setRxZmqPort,
(void (Detector::*)(int, int)) & Detector::setRxZmqPort,
py::arg(), py::arg() = -1);
CppDetectorApi.def(
"getRxZmqIP",
@ -1049,11 +1048,11 @@ void init_det(py::module &m) {
Detector::setRxZmqIP,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getClientZmqPort",
(Result<uint16_t>(Detector::*)(sls::Positions) const) &
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getClientZmqPort,
py::arg() = Positions{});
CppDetectorApi.def("setClientZmqPort",
(void (Detector::*)(uint16_t, int)) &
(void (Detector::*)(int, int)) &
Detector::setClientZmqPort,
py::arg(), py::arg() = -1);
CppDetectorApi.def(
@ -1270,16 +1269,6 @@ void init_det(py::module &m) {
(void (Detector::*)(int, sls::Positions)) &
Detector::setNumberOfFilterCells,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def(
"getPedestalMode",
(Result<defs::pedestalParameters>(Detector::*)(sls::Positions) const) &
Detector::getPedestalMode,
py::arg() = Positions{});
CppDetectorApi.def(
"setPedestalMode",
(void (Detector::*)(const defs::pedestalParameters, sls::Positions)) &
Detector::setPedestalMode,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getROI",
(Result<defs::ROI>(Detector::*)(sls::Positions) const) &
Detector::getROI,
@ -1535,21 +1524,29 @@ void init_det(py::module &m) {
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getSYNCClock,
py::arg() = Positions{});
CppDetectorApi.def("getPowerList",
CppDetectorApi.def("getADCPipeline",
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getADCPipeline,
py::arg() = Positions{});
CppDetectorApi.def("setADCPipeline",
(void (Detector::*)(int, sls::Positions)) &
Detector::setADCPipeline,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getVoltageList",
(std::vector<defs::dacIndex>(Detector::*)() const) &
Detector::getPowerList);
Detector::getVoltageList);
CppDetectorApi.def("getSlowADCList",
(std::vector<defs::dacIndex>(Detector::*)() const) &
Detector::getSlowADCList);
CppDetectorApi.def(
"getPower",
"getVoltage",
(Result<int>(Detector::*)(defs::dacIndex, sls::Positions) const) &
Detector::getPower,
Detector::getVoltage,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def(
"setPower",
"setVoltage",
(void (Detector::*)(defs::dacIndex, int, sls::Positions)) &
Detector::setPower,
Detector::setVoltage,
py::arg(), py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getADCVpp",
(Result<int>(Detector::*)(bool, sls::Positions) const) &
@ -1617,9 +1614,9 @@ void init_det(py::module &m) {
Detector::setDBITClock,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def(
"getMeasuredPower",
"getMeasuredVoltage",
(Result<int>(Detector::*)(defs::dacIndex, sls::Positions) const) &
Detector::getMeasuredPower,
Detector::getMeasuredVoltage,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def(
"getMeasuredCurrent",
@ -1736,26 +1733,26 @@ void init_det(py::module &m) {
(std::string(Detector::*)(const int) const) &
Detector::getSignalName,
py::arg());
CppDetectorApi.def("setPowerNames",
CppDetectorApi.def("setVoltageNames",
(void (Detector::*)(const std::vector<std::string>)) &
Detector::setPowerNames,
Detector::setVoltageNames,
py::arg());
CppDetectorApi.def("getPowerNames",
CppDetectorApi.def("getVoltageNames",
(std::vector<std::string>(Detector::*)() const) &
Detector::getPowerNames);
Detector::getVoltageNames);
CppDetectorApi.def(
"getPowerIndex",
"getVoltageIndex",
(defs::dacIndex(Detector::*)(const std::string &) const) &
Detector::getPowerIndex,
Detector::getVoltageIndex,
py::arg());
CppDetectorApi.def(
"setPowerName",
"setVoltageName",
(void (Detector::*)(const defs::dacIndex, const std::string &)) &
Detector::setPowerName,
Detector::setVoltageName,
py::arg(), py::arg());
CppDetectorApi.def("getPowerName",
CppDetectorApi.def("getVoltageName",
(std::string(Detector::*)(const defs::dacIndex) const) &
Detector::getPowerName,
Detector::getVoltageName,
py::arg());
CppDetectorApi.def("setSlowADCNames",
(void (Detector::*)(const std::vector<std::string>)) &
@ -1894,14 +1891,6 @@ void init_det(py::module &m) {
sls::Positions)) &
Detector::setAdditionalJsonParameter,
py::arg(), py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getADCPipeline",
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getADCPipeline,
py::arg() = Positions{});
CppDetectorApi.def("setADCPipeline",
(void (Detector::*)(int, sls::Positions)) &
Detector::setADCPipeline,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def(
"programFPGA",
(void (Detector::*)(const std::string &, const bool, sls::Positions)) &
@ -1989,19 +1978,19 @@ void init_det(py::module &m) {
Detector::setADCInvert,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getControlPort",
(Result<uint16_t>(Detector::*)(sls::Positions) const) &
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getControlPort,
py::arg() = Positions{});
CppDetectorApi.def("setControlPort",
(void (Detector::*)(uint16_t, sls::Positions)) &
(void (Detector::*)(int, sls::Positions)) &
Detector::setControlPort,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getStopPort",
(Result<uint16_t>(Detector::*)(sls::Positions) const) &
(Result<int>(Detector::*)(sls::Positions) const) &
Detector::getStopPort,
py::arg() = Positions{});
CppDetectorApi.def("setStopPort",
(void (Detector::*)(uint16_t, sls::Positions)) &
(void (Detector::*)(int, sls::Positions)) &
Detector::setStopPort,
py::arg(), py::arg() = Positions{});
CppDetectorApi.def("getDetectorLock",

View File

@ -19,8 +19,6 @@ void init_pattern(py::module &);
void init_scan(py::module &);
void init_source(py::module &);
void init_duration(py::module &);
void init_pedestal(py::module &);
PYBIND11_MODULE(_slsdet, m) {
m.doc() = R"pbdoc(
C/C++ API
@ -39,7 +37,6 @@ PYBIND11_MODULE(_slsdet, m) {
init_scan(m);
init_source(m);
init_duration(m);
init_pedestal(m);
// init_experimental(m);
py::module io = m.def_submodule("io", "Submodule for io");

View File

@ -1,23 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "py_headers.h"
#include "sls/ToString.h"
#include "sls/sls_detector_defs.h"
namespace py = pybind11;
void init_pedestal(py::module &m) {
using src = slsDetectorDefs::pedestalParameters;
py::class_<src> pedestalParameters(m, "pedestalParameters");
pedestalParameters.def(py::init());
pedestalParameters.def_readwrite("enable", &src::enable);
pedestalParameters.def_readwrite("frames", &src::frames);
pedestalParameters.def_readwrite("loops", &src::loops);
pedestalParameters.def(pybind11::self == pybind11::self);
pedestalParameters.def("__repr__",
[](const src &a) { return sls::ToString(a); });
}

View File

@ -193,7 +193,6 @@ void qDrawPlot::SetupPlots() {
gainplot2d = new SlsQt2DPlot(boxPlot, true);
gainplot2d->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, -0.5,
nPixelsY - 0.5, gainData);
gainplot2d->Update();
gainplot2d->hide();
connect(plot2d, SIGNAL(PlotZoomedSignal(const QRectF &)), this,
SLOT(Zoom2DGainPlot(const QRectF &)));
@ -1010,7 +1009,6 @@ void qDrawPlot::Update2dPlot() {
if (isGainDataExtracted) {
gainplot2d->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, -0.5,
nPixelsY - 0.5, gainData);
gainplot2d->Update();
if (!gainplot2d->isVisible()) {
gainplot2d->setFixedWidth(plot2d->width() /
qDefs::DATA_GAIN_PLOT_RATIO);

View File

@ -803,9 +803,8 @@ void qTabMeasurement::GetNextFrameNumber() {
"Inconsistent starting frame number for all detectors.");
spinNextFrameNumber->setValue(retval);
}
CATCH_HANDLE("Could not get starting frame number.",
"qTabMeasurement::GetNextFrameNumber", spinNextFrameNumber,
&QSpinBox::setValue, -1)
CATCH_DISPLAY("Could not get starting frame number.",
"qTabMeasurement::GetNextFrameNumber")
connect(spinNextFrameNumber, SIGNAL(valueChanged(int)), this,
SLOT(SetNextFrameNumber(int)));
}

View File

@ -11,7 +11,6 @@ install(TARGETS slsProjectCSettings
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
add_subdirectory(ctbDetectorServer)
add_subdirectory(xilinx_ctbDetectorServer)
add_subdirectory(eigerDetectorServer)
add_subdirectory(gotthardDetectorServer)
add_subdirectory(jungfrauDetectorServer)

View File

@ -1789,8 +1789,8 @@ int configureMAC() {
uint32_t dstip = udpDetails[0].dstip;
uint64_t srcmac = udpDetails[0].srcmac;
uint64_t dstmac = udpDetails[0].dstmac;
uint16_t srcport = udpDetails[0].srcport;
uint16_t dstport = udpDetails[0].dstport;
int srcport = udpDetails[0].srcport;
int dstport = udpDetails[0].dstport;
LOG(logINFOBLUE, ("Configuring MAC\n"));
char src_mac[MAC_ADDRESS_SIZE], src_ip[INET_ADDRSTRLEN],
@ -1802,10 +1802,10 @@ int configureMAC() {
LOG(logINFO, ("\tSource IP : %s\n"
"\tSource MAC : %s\n"
"\tSource Port : %hu\n"
"\tSource Port : %d\n"
"\tDest IP : %s\n"
"\tDest MAC : %s\n"
"\tDest Port : %hu\n",
"\tDest Port : %d\n",
src_ip, src_mac, srcport, dst_ip, dst_mac, dstport));
// 1 giga udp

View File

@ -1808,9 +1808,9 @@ int configureMAC() {
uint32_t dstip = udpDetails[iRxEntry].dstip;
uint64_t srcmac = udpDetails[iRxEntry].srcmac;
uint64_t dstmac = udpDetails[iRxEntry].dstmac;
uint16_t srcport = udpDetails[iRxEntry].srcport;
uint16_t dstport = udpDetails[iRxEntry].dstport;
uint16_t dstport2 = udpDetails[iRxEntry].dstport2;
int srcport = udpDetails[iRxEntry].srcport;
int dstport = udpDetails[iRxEntry].dstport;
int dstport2 = udpDetails[iRxEntry].dstport2;
char src_mac[MAC_ADDRESS_SIZE], src_ip[INET_ADDRSTRLEN],
dst_mac[MAC_ADDRESS_SIZE], dst_ip[INET_ADDRSTRLEN];
@ -1824,11 +1824,11 @@ int configureMAC() {
LOG(logINFO,
("\tSource IP : %s\n"
"\tSource MAC : %s\n"
"\tSource Port : %hu\n"
"\tSource Port : %d\n"
"\tDest IP : %s\n"
"\tDest MAC : %s\n"
"\tDest Port : %hu\n"
"\tDest Port2 : %hu\n",
"\tDest Port : %d\n"
"\tDest Port2 : %d\n",
src_ip, src_mac, srcport, dst_ip, dst_mac, dstport, dstport2));
}

View File

@ -10,7 +10,7 @@
#define HARDWARE_VERSION_NAMES \
{ "FX70T", "FX30T" }
#define REQUIRED_FIRMWARE_VERSION (32)
#define REQUIRED_FIRMWARE_VERSION (31)
// virtual ones renamed for consistency
// real ones keep previous name for compatibility (already in production)
#ifdef VIRTUAL

View File

@ -1902,8 +1902,8 @@ void setFirstUDPDestination(int value) {
}
void setupHeader(int iRxEntry, int vetoInterface, uint32_t destip,
uint64_t destmac, uint16_t destport, uint64_t sourcemac,
uint32_t sourceip, uint16_t sourceport) {
uint64_t destmac, uint32_t destport, uint64_t sourcemac,
uint32_t sourceip, uint32_t sourceport) {
// start addr
uint32_t addr = BASE_UDP_RAM;
@ -1995,10 +1995,10 @@ int configureMAC() {
uint64_t srcmac2 = udpDetails[iRxEntry].srcmac2;
uint64_t dstmac = udpDetails[iRxEntry].dstmac;
uint64_t dstmac2 = udpDetails[iRxEntry].dstmac2;
uint16_t srcport = udpDetails[iRxEntry].srcport;
uint16_t srcport2 = udpDetails[iRxEntry].srcport2;
uint16_t dstport = udpDetails[iRxEntry].dstport;
uint16_t dstport2 = udpDetails[iRxEntry].dstport2;
int srcport = udpDetails[iRxEntry].srcport;
int srcport2 = udpDetails[iRxEntry].srcport2;
int dstport = udpDetails[iRxEntry].dstport;
int dstport2 = udpDetails[iRxEntry].dstport2;
char src_mac[MAC_ADDRESS_SIZE], src_ip[INET_ADDRSTRLEN],
dst_mac[MAC_ADDRESS_SIZE], dst_ip[INET_ADDRSTRLEN];
@ -2020,10 +2020,10 @@ int configureMAC() {
LOG(logINFO, ("\tData Interface \n"));
LOG(logINFO, ("\tSource IP : %s\n"
"\tSource MAC : %s\n"
"\tSource Port : %hu\n"
"\tSource Port : %d\n"
"\tDest IP : %s\n"
"\tDest MAC : %s\n"
"\tDest Port : %hu\n\n",
"\tDest Port : %d\n\n",
src_ip, src_mac, srcport, dst_ip, dst_mac, dstport));
if (getVetoStream()) {
@ -2039,10 +2039,10 @@ int configureMAC() {
LOG(logINFO,
("\tSource IP2 : %s\n"
"\tSource MAC2 : %s\n"
"\tSource Port2: %hu\n"
"\tSource Port2: %d\n"
"\tDest IP2 : %s\n"
"\tDest MAC2 : %s\n"
"\tDest Port2 : %hu\n\n",
"\tDest Port2 : %d\n\n",
src_ip2, src_mac2, srcport2, dst_ip2, dst_mac2, dstport2));
}
#ifdef VIRTUAL
@ -3323,27 +3323,6 @@ void *start_timer(void *arg) {
break;
}
// change gain and data for every frame
{
const int nchannels = NCHIP * NCHAN;
int gainVal = 0;
for (int i = 0; i < nchannels; ++i) {
if ((i % nchannels) < 400) {
gainVal = 1 + frameNr;
} else if ((i % nchannels) < 800) {
gainVal = 2 + frameNr;
} else {
gainVal = 3 + frameNr;
}
int dataVal =
*((uint16_t *)(imageData + i * sizeof(uint16_t)));
dataVal += frameNr;
int channelVal =
(dataVal & ~GAIN_VAL_MSK) | (gainVal << GAIN_VAL_OFST);
*((uint16_t *)(imageData + i * sizeof(uint16_t))) =
(uint16_t)channelVal;
}
}
// sleep for exposure time
struct timespec begin, end;
clock_gettime(CLOCK_REALTIME, &begin);

View File

@ -90,7 +90,6 @@ void basictests() {
"Could not map to memory. Cannot proceed. Check Firmware.\n");
LOG(logERROR, (initErrorMessage));
initError = FAIL;
return;
}
#ifndef VIRTUAL
// does check only if flag is 0 (by default), set by command line
@ -1426,8 +1425,8 @@ int configureMAC() {
uint32_t dstip = udpDetails[0].dstip;
uint64_t srcmac = udpDetails[0].srcmac;
uint64_t dstmac = udpDetails[0].dstmac;
uint16_t srcport = udpDetails[0].srcport;
uint16_t dstport = udpDetails[0].dstport;
int srcport = udpDetails[0].srcport;
int dstport = udpDetails[0].dstport;
LOG(logINFOBLUE, ("Configuring MAC\n"));
char src_mac[MAC_ADDRESS_SIZE], src_ip[INET_ADDRSTRLEN],
@ -1439,10 +1438,10 @@ int configureMAC() {
LOG(logINFO, ("\tSource IP : %s\n"
"\tSource MAC : %s\n"
"\tSource Port : %hu\n"
"\tSource Port : %d\n"
"\tDest IP : %s\n"
"\tDest MAC : %s\n"
"\tDest Port : %hu\n",
"\tDest Port : %d\n",
src_ip, src_mac, srcport, dst_ip, dst_mac, dstport));
#ifdef VIRTUAL

View File

@ -24,18 +24,16 @@
#define RUN_BUSY_OFST (0)
#define RUN_BUSY_MSK (0x00000001 << RUN_BUSY_OFST)
#define WAITING_FOR_TRIGGER_OFST (1)
#define WAITING_FOR_TRIGGER_OFST (3)
#define WAITING_FOR_TRIGGER_MSK (0x00000001 << WAITING_FOR_TRIGGER_OFST)
#define WAITING_FOR_START_FRAME_OFST (2)
#define WAITING_FOR_START_FRAME_MSK (0x00000001 << WAITING_FOR_START_FRAME_OFST)
#define ACQUIRING_FRAME_OFST (3) // Not used in software
#define ACQUIRING_FRAME_MSK (0x00000001 << ACQUIRING_FRAME_OFST)
#define WAITING_FOR_PERIOD_TO_ELAPSE_OFST (4) // Not used in software
#define WAITING_FOR_PERIOD_TO_ELAPSE_MSK (0x00000001 << WAITING_FOR_PERIOD_TO_ELAPSE_OFST)
#define STOPPED_OFST (8)
#define DELAYBEFORE_OFST (4) // Not used in software
#define DELAYBEFORE_MSK (0x00000001 << DELAYBEFORE_OFST) // Not used in software
#define DELAYAFTER_OFST (5) // Not used in software
#define DELAYAFTER_MSK (0x00000001 << DELAYAFTER_OFST) // Not used in software
#define STOPPED_OFST (15)
#define STOPPED_MSK (0x00000001 << STOPPED_OFST)
#define INTERNAL_STOP_OFST (9)
#define INTERNAL_STOP_MSK (0x00000001 << INTERNAL_STOP_OFST)
#define RUNMACHINE_BUSY_OFST (17)
#define RUNMACHINE_BUSY_MSK (0x00000001 << RUNMACHINE_BUSY_OFST)
/* Look at me register */
#define LOOK_AT_ME_REG (0x03 << MEM_MAP_SHIFT) // Not used in firmware or software
@ -257,17 +255,6 @@
#define PLL_CNTRL_ADDR_OFST (16)
#define PLL_CNTRL_ADDR_MSK (0x0000003F << PLL_CNTRL_ADDR_OFST)
/* Pedestal Mode Regiser */
#define PEDESTAL_MODE_REG (0x57 << MEM_MAP_SHIFT)
#define PEDESTAL_MODE_ITRTNS_OFST (0)
#define PEDESTAL_MODE_ITRTNS_MSK (0x0000FFFF << PEDESTAL_MODE_ITRTNS_OFST)
#define PEDESTAL_MODE_LNGTH_OFST (16)
#define PEDESTAL_MODE_LNGTH_MSK (0x000000FF << PEDESTAL_MODE_LNGTH_OFST)
#define PEDESTAL_MODE_ENBLE_OFST (31)
#define PEDESTAL_MODE_ENBLE_MSK (0x00000001 << PEDESTAL_MODE_ENBLE_OFST)
/* Config Register for chip 1.1 */
#define CONFIG_V11_REG (0x58 << MEM_MAP_SHIFT)

View File

@ -55,9 +55,6 @@ int32_t clkPhase[NUM_CLOCKS] = {};
int detPos[4] = {};
int chipConfigured = 0;
uint64_t normal_mode_frames = -1;
uint64_t normal_mode_triggers = -1;
int isInitCheckDone() { return initCheckDone; }
int getInitResult(char **mess) {
@ -88,7 +85,6 @@ void basictests() {
"Could not map to memory. Cannot proceed. Check Firmware.\n");
LOG(logERROR, (initErrorMessage));
initError = FAIL;
return;
}
#ifndef VIRTUAL
// does check only if flag is 0 (by default), set by command line
@ -559,13 +555,6 @@ void setupDetector() {
setFlipRows(DEFAULT_FLIP_ROWS);
setReadNRows(MAX_ROWS_PER_READOUT);
}
#ifdef VIRTUAL
// setting pedestalmode depends on previous values
bus_w(PEDESTAL_MODE_REG,
bus_r(PEDESTAL_MODE_REG) & ~PEDESTAL_MODE_ENBLE_MSK);
#endif
setPedestalMode(DEFAULT_PEDESTAL_MODE, DEFAULT_PEDESTAL_FRAMES,
DEFAULT_PEDESTAL_LOOPS);
}
int resetToDefaultDacs(int hardReset) {
@ -986,9 +975,6 @@ int getNextFrameNumber(uint64_t *retval) {
}
void setNumFrames(int64_t val) {
if (getPedestalMode()) {
return;
}
if (val > 0) {
LOG(logINFO, ("Setting number of frames %lld\n", (long long int)val));
set64BitReg(val, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG);
@ -1000,9 +986,6 @@ int64_t getNumFrames() {
}
void setNumTriggers(int64_t val) {
if (getPedestalMode()) {
return;
}
if (val > 0) {
LOG(logINFO, ("Setting number of triggers %lld\n", (long long int)val));
set64BitReg(val, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG);
@ -1456,9 +1439,6 @@ void setSynchronization(int enable) {
}
void setTiming(enum timingMode arg) {
if (getPedestalMode()) {
return;
}
switch (arg) {
case AUTO_TIMING:
LOG(logINFO, ("Set Timing: Auto\n"));
@ -1552,8 +1532,8 @@ int getPrimaryInterface() {
}
void setupHeader(int iRxEntry, enum interfaceType type, uint32_t destip,
uint64_t destmac, uint16_t destport, uint64_t sourcemac,
uint32_t sourceip, uint16_t sourceport) {
uint64_t destmac, uint32_t destport, uint64_t sourcemac,
uint32_t sourceip, uint32_t sourceport) {
// start addr
uint32_t addr = (type == INNER ? RXR_ENDPOINT_INNER_START_REG
@ -1648,10 +1628,10 @@ int configureMAC() {
uint64_t srcmac2 = udpDetails[iRxEntry].srcmac2;
uint64_t dstmac = udpDetails[iRxEntry].dstmac;
uint64_t dstmac2 = udpDetails[iRxEntry].dstmac2;
uint16_t srcport = udpDetails[iRxEntry].srcport;
uint16_t srcport2 = udpDetails[iRxEntry].srcport2;
uint16_t dstport = udpDetails[iRxEntry].dstport;
uint16_t dstport2 = udpDetails[iRxEntry].dstport2;
int srcport = udpDetails[iRxEntry].srcport;
int srcport2 = udpDetails[iRxEntry].srcport2;
int dstport = udpDetails[iRxEntry].dstport;
int dstport2 = udpDetails[iRxEntry].dstport2;
char src_mac[MAC_ADDRESS_SIZE], src_ip[INET_ADDRSTRLEN],
dst_mac[MAC_ADDRESS_SIZE], dst_ip[INET_ADDRSTRLEN];
@ -1675,10 +1655,10 @@ int configureMAC() {
: (selInterface ? "Not Used" : "Used")));
LOG(logINFO, ("\tSource IP : %s\n"
"\tSource MAC : %s\n"
"\tSource Port : %hu\n"
"\tSource Port : %d\n"
"\tDest IP : %s\n"
"\tDest MAC : %s\n"
"\tDest Port : %hu\n\n",
"\tDest Port : %d\n\n",
src_ip, src_mac, srcport, dst_ip, dst_mac, dstport));
LOG(logINFO,
@ -1688,10 +1668,10 @@ int configureMAC() {
LOG(logINFO,
("\tSource IP2 : %s\n"
"\tSource MAC2 : %s\n"
"\tSource Port2: %hu\n"
"\tSource Port2: %d\n"
"\tDest IP2 : %s\n"
"\tDest MAC2 : %s\n"
"\tDest Port2 : %hu\n\n",
"\tDest Port2 : %d\n\n",
src_ip2, src_mac2, srcport2, dst_ip2, dst_mac2, dstport2));
}
#ifdef VIRTUAL
@ -2533,82 +2513,6 @@ uint64_t getSelectCurrentSource() {
}
}
int getPedestalMode() {
return ((bus_r(PEDESTAL_MODE_REG) & PEDESTAL_MODE_ENBLE_MSK) >>
PEDESTAL_MODE_ENBLE_OFST);
}
void getPedestalParameters(uint8_t *frames, uint16_t *loops) {
uint32_t addr = PEDESTAL_MODE_REG;
*frames =
((bus_r(addr) & PEDESTAL_MODE_LNGTH_MSK) >> PEDESTAL_MODE_LNGTH_OFST);
*loops = ((bus_r(PEDESTAL_MODE_REG) & PEDESTAL_MODE_ITRTNS_MSK) >>
PEDESTAL_MODE_ITRTNS_OFST);
}
void setPedestalMode(int enable, uint8_t frames, uint16_t loops) {
int prevPedestalEnable = getPedestalMode();
uint32_t addr = PEDESTAL_MODE_REG;
if (enable) {
LOG(logINFOBLUE, ("Enabling pedestal mode [frames: %hhu, loops: %hu]\n",
frames, loops));
// frames
bus_w(addr, bus_r(addr) & ~PEDESTAL_MODE_LNGTH_MSK);
bus_w(addr, bus_r(addr) | ((frames << PEDESTAL_MODE_LNGTH_OFST) &
PEDESTAL_MODE_LNGTH_MSK));
// loops
bus_w(addr, bus_r(addr) & ~PEDESTAL_MODE_ITRTNS_MSK);
bus_w(addr, bus_r(addr) | ((loops << PEDESTAL_MODE_ITRTNS_OFST) &
PEDESTAL_MODE_ITRTNS_MSK));
// enable
bus_w(addr, bus_r(addr) | PEDESTAL_MODE_ENBLE_MSK);
// if it was switched off before, remember the #frames and #triggers
if (prevPedestalEnable == 0) {
normal_mode_frames = getNumFrames();
normal_mode_triggers = getNumTriggers();
LOG(logINFO, ("\tRemembering Normal mode #frames and "
"#triggers[%lld, %lld]\n",
normal_mode_frames, normal_mode_triggers));
}
// overwrite #frames and #triggers to new values
int64_t expFrames = -1;
int64_t expTriggers = -1;
enum timingMode timing = getTiming();
if (timing == AUTO_TIMING ||
(timing == TRIGGER_EXPOSURE && normal_mode_frames > 1)) {
expFrames = frames * loops * 2;
expTriggers = 1;
} else {
expFrames = 1;
expTriggers = frames * loops * 2;
}
LOG(logINFO, ("\tOverwriting [#frames: %lld, #triggers: %lld]\n",
expFrames, expTriggers));
set64BitReg(expFrames, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG);
set64BitReg(expTriggers, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG);
} else {
LOG(logINFOBLUE, ("Disabling pedestal mode\n"));
bus_w(addr, bus_r(addr) & ~PEDESTAL_MODE_ENBLE_MSK);
// if it was switched on before, reset the normal mode #frames and
// #triggers
if (prevPedestalEnable == 1) {
LOG(logINFO,
("\tResetting to Normal mode [#frames:%lld, #triggers:%lld\n",
normal_mode_frames, normal_mode_triggers));
set64BitReg(normal_mode_frames, SET_FRAMES_LSB_REG,
SET_FRAMES_MSB_REG);
set64BitReg(normal_mode_triggers, SET_CYCLES_LSB_REG,
SET_CYCLES_MSB_REG);
}
}
}
int getTenGigaFlowControl() {
return ((bus_r(CONFIG_REG) & CONFIG_ETHRNT_FLW_CNTRL_MSK) >>
CONFIG_ETHRNT_FLW_CNTRL_OFST);
@ -2728,7 +2632,6 @@ void *start_timer(void *arg) {
if (i % pixelsPerPacket == 0) {
++dataVal;
}
if ((i % 1024) < 300) {
gainVal = 1;
} else if ((i % 1024) < 600) {
@ -2769,28 +2672,6 @@ void *start_timer(void *arg) {
clock_gettime(CLOCK_REALTIME, &begin);
usleep(expUs);
// change gain and data for every frame
{
const int npixels = (NCHAN * NCHIP);
for (int i = 0; i < npixels; ++i) {
int gainVal = 0;
if ((i % 1024) < 300) {
gainVal = 1 + iframes;
} else if ((i % 1024) < 600) {
gainVal = 2 + iframes;
} else {
gainVal = 3 + iframes;
}
int dataVal =
*((uint16_t *)(imageData + i * sizeof(uint16_t)));
dataVal += iframes;
int pixelVal =
(dataVal & ~GAIN_VAL_MSK) | (gainVal << GAIN_VAL_OFST);
*((uint16_t *)(imageData + i * sizeof(uint16_t))) =
(uint16_t)pixelVal;
}
}
int srcOffset = 0;
int srcOffset2 = DATA_BYTES / 2;
int row0 = (numInterfaces == 1 ? detPos[1] : detPos[3]);
@ -2925,17 +2806,14 @@ int softwareTrigger(int block) {
LOG(logINFO, ("Sending Software Trigger\n"));
bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_SOFTWARE_TRIGGER_MSK);
bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_SOFTWARE_TRIGGER_MSK);
// wait to make sure its out of this state and even 'wait for start frame'
usleep(100);
#ifndef VIRTUAL
// block till frame sent out & back to wait for trigger (or not busy
// anymore)
// block till frame is sent out
if (block) {
uint32_t retval = bus_r(STATUS_REG);
while ((retval & RUN_BUSY_MSK) && !(retval & WAITING_FOR_TRIGGER_MSK)) {
enum runStatus s = getRunStatus();
while (s == RUNNING || s == TRANSMITTING) {
usleep(5000);
retval = bus_r(STATUS_REG);
s = getRunStatus();
}
}
LOG(logINFO, ("Ready for Next Trigger...\n"));
@ -2968,16 +2846,9 @@ enum runStatus getRunStatus() {
u_int32_t retval = bus_r(STATUS_REG);
LOG(logINFO, ("Status Register: %08x\n", retval));
// error
if (retval & INTERNAL_STOP_MSK) {
LOG(logINFOBLUE, ("Status: ERROR\n"));
s = ERROR;
}
// running
else if (retval & RUN_BUSY_MSK) {
if ((retval & WAITING_FOR_TRIGGER_MSK) ||
(retval & WAITING_FOR_START_FRAME_MSK)) {
if (retval & RUN_BUSY_MSK) {
if (retval & WAITING_FOR_TRIGGER_MSK) {
LOG(logINFOBLUE, ("Status: WAITING\n"));
s = WAITING;
} else {
@ -2988,13 +2859,19 @@ enum runStatus getRunStatus() {
// not running
else {
// stopped or idle
// stopped or error
if (retval & STOPPED_MSK) {
LOG(logINFOBLUE, ("Status: STOPPED\n"));
s = STOPPED;
} else {
} else if (retval & RUNMACHINE_BUSY_MSK) {
LOG(logINFOBLUE, ("Status: READ MACHINE BUSY\n"));
s = TRANSMITTING;
} else if (!retval) {
LOG(logINFOBLUE, ("Status: IDLE\n"));
s = IDLE;
} else {
LOG(logERROR, ("Status: Unknown status %08x\n", retval));
s = ERROR;
}
}

View File

@ -5,8 +5,8 @@
#include "sls/sls_detector_defs.h"
#define MIN_REQRD_VRSN_T_RD_API 0x171220
#define REQRD_FRMWRE_VRSN_BOARD2 0x230920 // 1.0 pcb (version = 010)
#define REQRD_FRMWRE_VRSN 0x230921 // 2.0 pcb (version = 011)
#define REQRD_FRMWRE_VRSN_BOARD2 0x230516 // 1.0 pcb (version = 010)
#define REQRD_FRMWRE_VRSN 0x230515 // 2.0 pcb (version = 011)
#define NUM_HARDWARE_VERSIONS (2)
#define HARDWARE_VERSION_NUMBERS \
@ -52,9 +52,6 @@
#define DEFAULT_FLIP_ROWS (0)
#define DEFAULT_FILTER_RESISTOR (1) // higher resistor
#define DEFAULT_FILTER_CELL (0)
#define DEFAULT_PEDESTAL_MODE (0)
#define DEFAULT_PEDESTAL_FRAMES (1)
#define DEFAULT_PEDESTAL_LOOPS (1)
#define HIGHVOLTAGE_MIN (60)
#define HIGHVOLTAGE_MAX (200)

View File

@ -82,7 +82,6 @@ void basictests() {
"Could not map to memory. Cannot proceed. Check Firmware.\n");
LOG(logERROR, ("%s\n\n", initErrorMessage));
initError = FAIL;
return;
}
#ifndef VIRTUAL
// does check only if flag is 0 (by default), set by command line
@ -700,12 +699,14 @@ int setExpTime(int64_t val) {
}
LOG(logINFO, ("Setting exptime %lld ns\n", (long long int)val));
val *= (1E-3 * CLK_RUN);
val -= ACQ_TIME_MIN_CLOCK;
if (val < 0) {
val = 0;
}
set64BitReg(val, SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG);
// validate for tolerance
val += ACQ_TIME_MIN_CLOCK;
int64_t retval = getExpTime();
val /= (1E-3 * CLK_RUN);
if (val != retval) {
@ -715,7 +716,8 @@ int setExpTime(int64_t val) {
}
int64_t getExpTime() {
return get64BitReg(SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) /
return (get64BitReg(SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) +
ACQ_TIME_MIN_CLOCK) /
(1E-3 * CLK_RUN);
}
@ -1118,8 +1120,8 @@ int getPrimaryInterface() {
}
void setupHeader(int iRxEntry, enum interfaceType type, uint32_t destip,
uint64_t destmac, uint16_t destport, uint64_t sourcemac,
uint32_t sourceip, uint16_t sourceport) {
uint64_t destmac, uint32_t destport, uint64_t sourcemac,
uint32_t sourceip, uint32_t sourceport) {
// start addr
uint32_t addr = (type == INNER ? RXR_ENDPOINT_INNER_START_REG
@ -1214,10 +1216,10 @@ int configureMAC() {
uint64_t srcmac2 = udpDetails[iRxEntry].srcmac2;
uint64_t dstmac = udpDetails[iRxEntry].dstmac;
uint64_t dstmac2 = udpDetails[iRxEntry].dstmac2;
uint16_t srcport = udpDetails[iRxEntry].srcport;
uint16_t srcport2 = udpDetails[iRxEntry].srcport2;
uint16_t dstport = udpDetails[iRxEntry].dstport;
uint16_t dstport2 = udpDetails[iRxEntry].dstport2;
int srcport = udpDetails[iRxEntry].srcport;
int srcport2 = udpDetails[iRxEntry].srcport2;
int dstport = udpDetails[iRxEntry].dstport;
int dstport2 = udpDetails[iRxEntry].dstport2;
char src_mac[MAC_ADDRESS_SIZE], src_ip[INET_ADDRSTRLEN],
dst_mac[MAC_ADDRESS_SIZE], dst_ip[INET_ADDRSTRLEN];
@ -1241,10 +1243,10 @@ int configureMAC() {
: (selInterface ? "Not Used" : "Used")));
LOG(logINFO, ("\tSource IP : %s\n"
"\tSource MAC : %s\n"
"\tSource Port : %hu\n"
"\tSource Port : %d\n"
"\tDest IP : %s\n"
"\tDest MAC : %s\n"
"\tDest Port : %hu\n\n",
"\tDest Port : %d\n\n",
src_ip, src_mac, srcport, dst_ip, dst_mac, dstport));
LOG(logINFO,
@ -1254,10 +1256,10 @@ int configureMAC() {
LOG(logINFO,
("\tSource IP2 : %s\n"
"\tSource MAC2 : %s\n"
"\tSource Port2: %hu\n"
"\tSource Port2: %d\n"
"\tDest IP2 : %s\n"
"\tDest MAC2 : %s\n"
"\tDest Port2 : %hu\n\n",
"\tDest Port2 : %d\n\n",
src_ip2, src_mac2, srcport2, dst_ip2, dst_mac2, dstport2));
}
#ifdef VIRTUAL

View File

@ -5,7 +5,7 @@
#include "sls/sls_detector_defs.h"
#define REQRD_FRMWRE_VRSN_BOARD2 0x444445 // 1.0 pcb (version = 010)
#define REQRD_FRMWRE_VRSN 0x231026 // 2.0 pcb (version = 011)
#define REQRD_FRMWRE_VRSN 0x230710 // 2.0 pcb (version = 011)
#define NUM_HARDWARE_VERSIONS (2)
#define HARDWARE_VERSION_NUMBERS \
@ -58,6 +58,7 @@
/* Defines in the Firmware */
#define MAX_TIMESLOT_VAL (0x1F)
#define MAX_THRESHOLD_TEMP_VAL (127999) // millidegrees
#define ACQ_TIME_MIN_CLOCK (2)
#define ASIC_FILTER_MAX_RES_VALUE (1)
#define MAX_SELECT_CHIP10_VAL (63)

View File

@ -92,7 +92,6 @@ void basictests() {
"Could not map to memory. Cannot proceed. Check Firmware.\n");
LOG(logERROR, (initErrorMessage));
initError = FAIL;
return;
}
#ifndef VIRTUAL
// does check only if flag is 0 (by default), set by command line
@ -1964,8 +1963,8 @@ int configureMAC() {
uint32_t dstip = udpDetails[iRxEntry].dstip;
uint64_t srcmac = udpDetails[iRxEntry].srcmac;
uint64_t dstmac = udpDetails[iRxEntry].dstmac;
uint16_t srcport = udpDetails[iRxEntry].srcport;
uint16_t dstport = udpDetails[iRxEntry].dstport;
int srcport = udpDetails[iRxEntry].srcport;
int dstport = udpDetails[iRxEntry].dstport;
char src_mac[MAC_ADDRESS_SIZE], src_ip[INET_ADDRSTRLEN],
dst_mac[MAC_ADDRESS_SIZE], dst_ip[INET_ADDRSTRLEN];
@ -1977,10 +1976,10 @@ int configureMAC() {
LOG(logINFOBLUE, ("\tEntry %d\n", iRxEntry));
LOG(logINFO, ("\tSource IP : %s\n"
"\tSource MAC : %s\n"
"\tSource Port : %hu\n"
"\tSource Port : %d\n"
"\tDest IP : %s\n"
"\tDest MAC : %s\n"
"\tDest Port : %hu\n",
"\tDest Port : %d\n",
src_ip, src_mac, srcport, dst_ip, dst_mac, dstport));
}
#ifdef VIRTUAL

View File

@ -1,10 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#include <inttypes.h>
#include <sys/types.h>
int mapCSP0(void);
void bus_w(u_int32_t offset, u_int32_t data);
u_int32_t bus_r(u_int32_t offset);

View File

@ -25,10 +25,6 @@
#include "blackfin.h"
#endif
#ifdef ARMPROCESSOR
#include "arm64.h"
#endif
#ifdef MYTHEN3D
#include "mythen3.h"
#endif
@ -46,10 +42,10 @@ single detector.
enum interfaceType { OUTER, INNER };
typedef struct udpStruct_s {
uint16_t srcport;
uint16_t srcport2;
uint16_t dstport;
uint16_t dstport2;
int srcport;
int srcport2;
int dstport;
int dstport2;
uint64_t srcmac;
uint64_t srcmac2;
uint64_t dstmac;
@ -65,10 +61,9 @@ typedef struct udpStruct_s {
int isInitCheckDone();
int getInitResult(char **mess);
void basictests();
int checkType();
#if defined(GOTTHARDD) || defined(JUNGFRAUD) || defined(MOENCHD) || \
defined(CHIPTESTBOARDD) || defined(MYTHEN3D) || defined(GOTTHARD2D)
int checkType();
int testFpga();
int testBus();
#endif
@ -86,17 +81,13 @@ u_int64_t getFirmwareVersion();
#ifdef EIGERD
uint64_t getFrontEndFirmwareVersion(enum fpgaPosition fpgaPosition);
#endif
#ifndef XILINX_CHIPTESTBOARDD
u_int64_t getFirmwareAPIVersion();
void getHardwareVersion(char *version);
#endif
#ifdef EIGERD
int getHardwareVersionNumber();
#else
#ifndef XILINX_CHIPTESTBOARDD
u_int16_t getHardwareVersionNumber();
#endif
#endif
#if defined(JUNGFRAUD) || defined(MOENCHD) || defined(CHIPTESTBOARDD)
u_int16_t getHardwareSerialNumber();
#endif
@ -120,6 +111,7 @@ int updateModuleId();
void setModuleId(int modid);
#endif
#endif
u_int64_t getDetectorMAC();
u_int32_t getDetectorIP();
@ -144,7 +136,7 @@ int updateDatabytesandAllocateRAM();
void updateDataBytes();
#endif
#if !defined(CHIPTESTBOARDD) && !defined(XILINX_CHIPTESTBOARDD)
#ifndef CHIPTESTBOARDD
int resetToDefaultDacs(int hardReset);
int getDefaultDac(enum DACINDEX index, enum detectorSettings sett, int *retval);
int setDefaultDac(enum DACINDEX index, enum detectorSettings sett, int value);
@ -199,10 +191,8 @@ void setMasterSlaveConfiguration();
#endif
// parameters - dr, roi
#ifndef XILINX_CHIPTESTBOARDD
int setDynamicRange(int dr);
int getDynamicRange(int *retval);
#endif
#ifdef GOTTHARDD
int setROI(ROI arg);
ROI getROI();
@ -251,7 +241,6 @@ int getMaxStoragecellStart();
int setNextFrameNumber(uint64_t value);
int getNextFrameNumber(uint64_t *value);
#endif
#ifndef XILINX_CHIPTESTBOARDD
void setNumFrames(int64_t val);
int64_t getNumFrames();
void setNumTriggers(int64_t val);
@ -262,7 +251,6 @@ int64_t getExpTime();
#endif
int setPeriod(int64_t val);
int64_t getPeriod();
#endif
#ifdef MYTHEN3D
void setNumIntGates(int val);
void setNumGates(int val);
@ -349,12 +337,10 @@ int setTrimbits(int *trimbits);
int setAllTrimbits(int val);
int getAllTrimbits();
#endif
#ifndef XILINX_CHIPTESTBOARDD
#ifndef CHIPTESTBOARDD
enum detectorSettings setSettings(enum detectorSettings sett);
#endif
enum detectorSettings getSettings();
#endif
#if defined(JUNGFRAUD)
enum gainMode getGainMode();
void setGainMode(enum gainMode mode);
@ -380,14 +366,10 @@ void setDAC(enum DACINDEX ind, int val, int mV, int counterEnableCheck);
void setGeneralDAC(enum DACINDEX ind, int val, int mV);
void setVthDac(int index, int enable);
#else
#ifndef XILINX_CHIPTESTBOARDD
void setDAC(enum DACINDEX ind, int val, int mV);
#endif
#endif
#ifndef XILINX_CHIPTESTBOARDD
int getDAC(enum DACINDEX ind, int mV);
int getMaxDacSteps();
#endif
#if defined(CHIPTESTBOARDD)
int dacToVoltage(int dac);
int checkVLimitCompliant(int mV);
@ -412,17 +394,14 @@ void powerOff();
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
int getADC(enum ADCINDEX ind, int *value);
#else
#ifndef XILINX_CHIPTESTBOARDD
int getADC(enum ADCINDEX ind);
#endif
#endif
#ifdef CHIPTESTBOARDD
int getSlowADC(int ichan);
int getSlowADCTemperature();
#endif
#ifndef XILINX_CHIPTESTBOARDD
int setHighVoltage(int val);
#endif
// parameters - timing, extsig
#if defined(EIGERD) || defined(GOTTHARD2D) || defined(JUNGFRAUD) || \
@ -447,10 +426,8 @@ void setSynchronization(int enable);
void updatingRegisters();
int updateClockDivs();
#endif
#ifndef XILINX_CHIPTESTBOARDD
void setTiming(enum timingMode arg);
enum timingMode getTiming();
#endif
#ifdef MYTHEN3D
void setInitialExtSignals();
int setChipStatusRegister(int csr);
@ -490,8 +467,8 @@ void setFirstUDPDestination(int value);
void selectPrimaryInterface(int val);
int getPrimaryInterface();
void setupHeader(int iRxEntry, enum interfaceType type, uint32_t destip,
uint64_t destmac, uint16_t destport, uint64_t sourcemac,
uint32_t sourceip, uint16_t sourceport);
uint64_t destmac, uint32_t destport, uint64_t sourcemac,
uint32_t sourceip, uint32_t sourceport);
#endif
#if defined(JUNGFRAUD) || defined(MOENCHD) || defined(GOTTHARD2D) || \
defined(MYTHEN3D) || defined(CHIPTESTBOARDD)
@ -501,9 +478,7 @@ void calcChecksum(udp_header *udp);
int getAdcConfigured();
#endif
#ifndef XILINX_CHIPTESTBOARDD
int configureMAC();
#endif
int setDetectorPosition(int pos[]);
int *getDetectorPosition();
@ -541,7 +516,7 @@ void setDigitalIODelay(uint64_t pinMask, int delay);
// jungfrau/moench specific - powerchip, autocompdisable, clockdiv, asictimer,
// clock, pll, flashing firmware
#if defined(MOENCHD)
#if defined(MOENCHED)
void setADCPipeline(int val);
int getADCPipeline();
#endif
@ -581,9 +556,6 @@ int getCurrentSource();
int getFixCurrentSource();
int getNormalCurrentSource();
uint64_t getSelectCurrentSource();
int getPedestalMode();
void getPedestalParameters(uint8_t *frames, uint16_t *loops);
void setPedestalMode(int enable, uint8_t frames, uint16_t loops);
#endif
// eiger specific - iodelay, pulse, rate, temp, activate, delay nw parameter
@ -699,13 +671,11 @@ int setTransmissionDelayRight(int value);
#endif
// aquisition
#ifndef XILINX_CHIPTESTBOARDD
int startStateMachine();
#ifdef VIRTUAL
void *start_timer(void *arg);
#endif
int stopStateMachine();
#endif
#ifdef MYTHEN3D
int softwareTrigger();
#endif
@ -715,16 +685,12 @@ int softwareTrigger(int block);
#if defined(EIGERD) || defined(MYTHEN3D) || defined(CHIPTESTBOARDD)
int startReadOut();
#endif
#ifndef XILINX_CHIPTESTBOARDD
enum runStatus getRunStatus();
#endif
#ifdef EIGERD
void waitForAcquisitionEnd(int *ret, char *mess);
#else
#ifndef XILINX_CHIPTESTBOARDD
void waitForAcquisitionEnd();
#endif
#endif
#if defined(CHIPTESTBOARDD)
int validateUDPSocket();
void readandSendUDPFrames();
@ -745,7 +711,6 @@ u_int32_t runState(enum TLogLevel lev);
#endif
// common
#ifndef XILINX_CHIPTESTBOARDD
int calculateDataBytes();
int getTotalNumberOfChannels();
#if defined(CHIPTESTBOARDD)
@ -754,4 +719,3 @@ void getNumberOfChannels(int *nchanx, int *nchany);
int getNumberOfChips();
int getNumberOfDACs();
int getNumberOfChannelsPerChip();
#endif

View File

@ -327,5 +327,3 @@ int getRow();
int setRow(int);
int getColumn();
int setColumn(int);
int get_pedestal_mode(int);
int set_pedestal_mode(int);

View File

@ -1,75 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "arm64.h"
#include "RegisterDefs.h"
#include "clogger.h"
#include "common.h"
#include "sls/ansi.h"
#include "sls/sls_detector_defs.h"
#include <fcntl.h> // open
#include <sys/mman.h> // mmap
/* global variables */
#define CSP0 (0xB0010000)/// 0xB008_0000
#define MEM_SIZE 0x100000
u_int32_t *csp0base = 0;
void bus_w(u_int32_t offset, u_int32_t data) {
volatile u_int32_t *ptr1;
ptr1 = (u_int32_t *)(csp0base + offset / (sizeof(u_int32_t)));
*ptr1 = data;
}
u_int32_t bus_r(u_int32_t offset) {
volatile u_int32_t *ptr1;
ptr1 = (u_int32_t *)(csp0base + offset / (sizeof(u_int32_t)));
return *ptr1;
}
uint64_t getU64BitReg(int aLSB, int aMSB) {
uint64_t retval = bus_r(aMSB);
retval = (retval << 32) | bus_r(aLSB);
return retval;
}
void setU64BitReg(uint64_t value, int aLSB, int aMSB) {
bus_w(aLSB, value & (0xffffffff));
bus_w(aMSB, (value >> 32) & (0xffffffff));
}
int mapCSP0(void) {
// if not mapped
if (csp0base == 0) {
LOG(logINFO, ("Mapping memory\n"));
#ifdef VIRTUAL
csp0base = malloc(MEM_SIZE);
if (csp0base == NULL) {
LOG(logERROR, ("Could not allocate virtual memory.\n"));
return FAIL;
}
LOG(logINFO, ("memory allocated\n"));
#else
int fd;
fd = open("/dev/mem", O_RDWR | O_SYNC, 0);
if (fd == -1) {
LOG(logERROR, ("Can't find /dev/mem\n"));
return FAIL;
}
LOG(logDEBUG1, ("/dev/mem opened\n"));
csp0base = (u_int32_t*)mmap(0, MEM_SIZE, PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED, fd, CSP0);
if (csp0base == MAP_FAILED) {
LOG(logERROR, ("Can't map memmory area\n"));
return FAIL;
}
#endif
LOG(logINFO, ("csp0base mapped from %p to %p\n", csp0base,
(csp0base + MEM_SIZE)));
} else
LOG(logINFO, ("Memory already mapped before\n"));
return OK;
}

View File

@ -15,11 +15,6 @@ u_int32_t *csp0base = 0;
#define CSP0 0x20200000
#define MEM_SIZE 0x100000
#ifdef JUNGFRAUD
extern void configureChip();
#endif
void bus_w16(u_int32_t offset, u_int16_t data) {
volatile u_int16_t *ptr1;
ptr1 = (u_int16_t *)(csp0base + offset / 2);
@ -85,21 +80,7 @@ u_int32_t readRegister(u_int32_t offset) {
}
u_int32_t writeRegister(u_int32_t offset, u_int32_t data) {
// if electron mode bit touched
#ifdef JUNGFRAUD
int electronCollectionModeChange = 0;
if ((offset << MEM_MAP_SHIFT) == DAQ_REG) {
if ((readRegister(offset) ^ data) & DAQ_ELCTRN_CLLCTN_MDE_MSK) {
electronCollectionModeChange = 1;
}
}
#endif
bus_w(offset << MEM_MAP_SHIFT, data);
#ifdef JUNGFRAUD
if (electronCollectionModeChange) {
configureChip();
}
#endif
return readRegister(offset);
}

View File

@ -114,10 +114,6 @@ int getTimeFromString(char *buf, time_t *result) {
t.tm_mday, t.tm_mon, t.tm_year + 1900, t.tm_hour, t.tm_min, t.tm_sec));
*result = mktime(&t);
if (*result == -1) {
LOG(logERROR, ("Could not convert time structure to time_t\n"));
return FAIL;
}
return OK;
}
@ -134,7 +130,6 @@ int getKernelVersion(char *retvals) {
return OK;
}
int validateKernelVersion(char *expectedVersion) {
// extract kernel date string
char version[255] = {0};
@ -148,26 +143,15 @@ int validateKernelVersion(char *expectedVersion) {
#ifdef VIRTUAL
strcpy(currentVersion, expectedVersion);
#else
#ifndef ARMPROCESSOR
// remove first word (#version number)
const char *ptr = strstr(version, " ");
const char *ptr = strchr(version, ' ');
if (ptr == NULL) {
LOG(logERROR, ("Could not parse kernel version\n"));
return FAIL;
}
strcpy(currentVersion, ptr + 1);
#else
// remove first two words (#version number and SMP)
const char *ptr = strstr(version, "SMP ");
if (ptr == NULL) {
LOG(logERROR, ("Could not parse kernel version\n"));
return FAIL;
}
strcpy(currentVersion, ptr + 4);
strcpy(currentVersion, version + (ptr - version + 1));
#endif
#endif
currentVersion[sizeof(currentVersion) - 1] = '\0';
// convert kernel date string into time
time_t kernelDate;
if (getTimeFromString(currentVersion, &kernelDate) == FAIL) {
@ -175,7 +159,6 @@ int validateKernelVersion(char *expectedVersion) {
("Could not parse retrieved kernel date, %s\n", currentVersion));
return FAIL;
}
LOG(logDEBUG, ("Kernel Date: [%s]\n", ctime(&kernelDate)));
// convert expected date into time
time_t expDate;
@ -184,12 +167,11 @@ int validateKernelVersion(char *expectedVersion) {
("Could not parse expected kernel date, %s\n", expectedVersion));
return FAIL;
}
LOG(logDEBUG, ("Expected Date: [%s]\n", ctime(&expDate)));
// compare if kernel time is older than expected time
if (kernelDate < expDate) {
LOG(logERROR, ("Kernel Version Incompatible (too old)!\nExpected: '%s'"
"\nGot : '%s'\n",
LOG(logERROR, ("Kernel Version Incompatible (too old)! Expected: [%s], "
"Got [%s]\n",
expectedVersion, currentVersion));
return FAIL;
}

View File

@ -13,7 +13,6 @@
#include "slsDetectorServer_funcs.h"
#include <getopt.h>
#include <limits.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
@ -277,15 +276,6 @@ int main(int argc, char *argv[]) {
LOG(logERROR, ("Could not set handler function for SIGINT"));
}
// validate control and stop port number
if (0 >= portno || portno > USHRT_MAX || 0 >= (portno + 1) ||
(portno + 1) > USHRT_MAX) {
LOG(logERROR, ("Invalid control server or stop server port "
"numbers (%d, %d). It must be in range 1 - %d",
portno, portno + 1, USHRT_MAX));
return -1;
}
if (sharedMemory_create(portno) == FAIL) {
return -1;
}

View File

@ -1,38 +0,0 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
add_executable(xilinx_ctbDetectorServer_virtual
slsDetectorFunctionList.c
../slsDetectorServer/src/slsDetectorServer.c
../slsDetectorServer/src/slsDetectorServer_funcs.c
../slsDetectorServer/src/communication_funcs.c
../slsDetectorServer/src/arm64.c
../slsDetectorServer/src/common.c
../slsDetectorServer/src/sharedMemory.c
../../slsSupportLib/src/md5.c
)
include_directories(
../slsDetectorServer/include
../../slsSupportLib/include
../../slsDetectorSoftware/include/sls/
)
target_include_directories(xilinx_ctbDetectorServer_virtual
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
)
target_compile_definitions(xilinx_ctbDetectorServer_virtual
PUBLIC XILINX_CHIPTESTBOARDD ARMPROCESSOR VIRTUAL STOP_SERVER
)
target_link_libraries(xilinx_ctbDetectorServer_virtual
PUBLIC pthread rt slsProjectCSettings
)
set_target_properties(xilinx_ctbDetectorServer_virtual PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
install(TARGETS xilinx_ctbDetectorServer_virtual
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)

View File

@ -1,47 +0,0 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
current_dir = $(shell pwd)
main_inc = ../slsDetectorServer/include/
main_src = ../slsDetectorServer/src/
support_lib = ../../slsSupportLib/include/
det_lib = ../../slsDetectorSoftware/include/sls/
md5_dir = ../../slsSupportLib/src/
CROSS = aarch64-none-linux-gnu-
CC = $(CROSS)gcc
#TODO: allow these warnings and fix code
CFLAGS += -Wall -std=gnu99 -Wno-format-overflow -Wno-format-truncation -DXILINX_CHIPTESTBOARDD -DARMPROCESSOR -DSTOP_SERVER -I$(main_inc) -I$(support_lib) -I$(det_lib) -I$(current_dir) #-DDEBUG1 #-DVERBOSEI #-DVERBOSE
#CFLAGS += -Wall -std=gnu99 -DXILINX_CHIPTESTBOARDD -DARMPROCESSOR -DSTOP_SERVER -I$(main_inc) -I$(support_lib) -I$(det_lib) -I$(current_dir) #-DDEBUG1 #-DVERBOSEI #-DVERBOSE
LDLIBS += -lm -lrt -pthread
PROGS = xilinx_ctbDetectorServer
DESTDIR ?= bin
INSTMODE = 0777
SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)arm64.c $(main_src)common.c $(main_src)/sharedMemory.c $(md5_dir)md5.c
OBJS = $(SRCS:.c=.o)
all: clean $(PROGS)
version: clean versioning $(PROGS)
boot: $(OBJS)
version_branch=$(API_BRANCH)
version_name=APIXILINXCTB
version_path=slsDetectorServers/xilinx_ctbDetectorServer
versioning:
cd ../../ && echo $(PWD) && echo `tput setaf 6; ./updateAPIVersion.sh $(version_name) $(version_path) $(version_branch); tput sgr0;`
$(PROGS): $(OBJS)
# echo $(OBJS)
mkdir -p $(DESTDIR)
$(CC) -o $@ $^ $(CFLAGS) $(LDLIBS)
mv $(PROGS) $(DESTDIR)
rm $(main_src)*.o $(md5_dir)*.o
clean:
rm -rf $(DESTDIR)/$(PROGS) *.o *.gdb $(main_src)*.o $(md5_dir)*.o

View File

@ -1,416 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#define CTRLREG1 (0x0)
#define CTR1_OFST (0)
#define CTR1_MSK (0xffffffff << CTR1_OFST)
#define CTRLREG2 (0x4)
#define CTRL2_OFST (0)
#define CTRL2_MSK (0xffffffff << CTRL2_OFST)
#define STATUSREG1 (0x8)
#define STATUS1_OFST (0)
#define STATUS1_MSK (0xffffffff << STATUS1_OFST)
#define STATUSREG2 (0xC)
#define STATUS2_OFST (0)
#define STATUS2_MSK (0xffffffff << STATUS2_OFST)
#define FPGAVERSIONREG (0x10)
#define COMPDATE_OFST (0)
#define COMPDATE_MSK (0x00ffffff << COMPDATE_OFST)
#define DETTYPE_OFST (24)
#define DETTYPE_MSK (0x000000ff << DETTYPE_OFST)
#define PKTPACKETLENGTHREG (0x28)
#define PACKETLENGTH1G_OFST (0)
#define PACKETLENGTH1G_MSK (0x0000ffff << PACKETLENGTH1G_OFST)
#define PACKETLENGTH10G_OFST (16)
#define PACKETLENGTH10G_MSK (0x0000ffff << PACKETLENGTH10G_OFST)
#define PKTNOPACKETSREG (0x30)
#define NOPACKETS1G_OFST (0)
#define NOPACKETS1G_MSK (0x0000003f << NOPACKETS1G_OFST)
#define NOPACKETS10G_OFST (8)
#define NOPACKETS10G_MSK (0x0000003f << NOPACKETS10G_OFST)
#define PKTCTRLREG (0x38)
#define NSERVERS_OFST (0)
#define NSERVERS_MSK (0x0000003f << NSERVERS_OFST)
#define SERVERSTART_OFST (6)
#define SERVERSTART_MSK (0x0000001f << SERVERSTART_OFST)
#define ETHINTERF_OFST (11)
#define ETHINTERF_MSK (0x00000001 << ETHINTERF_OFST)
#define PKTCOORDREG1 (0x40)
#define COORDX_OFST (0)
#define COORDX_MSK (0x0000ffff << COORDX_OFST)
#define COORDY_OFST (16)
#define COORDY_MSK (0x0000ffff << COORDY_OFST)
#define PKTCOORDREG2 (0x48)
#define COORDZ_OFST (0)
#define COORDZ_MSK (0x0000ffff << COORDZ_OFST)
#define FLOWSTATUSREG (0x100)
#define RSMBUSY_OFST (0)
#define RSMBUSY_MSK (0x00000001 << RSMBUSY_OFST)
#define RSMTRGWAIT_OFST (3)
#define RSMTRGWAIT_MSK (0x00000001 << RSMTRGWAIT_OFST)
#define CSMBUSY_OFST (17)
#define CSMBUSY_MSK (0x00000001 << CSMBUSY_OFST)
#define FLOWCONTROLREG (0x108)
#define STARTF_OFST (0)
#define STARTF_MSK (0x00000001 << STARTF_OFST)
#define STOPF_OFST (1)
#define STOPF_MSK (0x00000001 << STOPF_OFST)
#define RSTF_OFST (2)
#define RSTF_MSK (0x00000001 << RSTF_OFST)
#define SWTRIGGERF_OFST (3)
#define SWTRIGGERF_MSK (0x00000001 << SWTRIGGERF_OFST)
#define TRIGGERENABLE_OFST (4)
#define TRIGGERENABLE_MSK (0x00000001 << TRIGGERENABLE_OFST)
#define TIMEFROMSTARTOUTREG1 (0x110)
#define TIMEFROMSTARTOUT1_OFST (0)
#define TIMEFROMSTARTOUT1_MSK (0xffffffff << TIMEFROMSTARTOUT1_OFST)
#define TIMEFROMSTARTOUTREG2 (0x114)
#define TIMEFROMSTARTOUT2_OFST (0)
#define TIMEFROMSTARTOUT2_MSK (0xffffffff << TIMEFROMSTARTOUT2_OFST)
#define FRAMESFROMSTARTOUTREG1 (0x118)
#define FRAMESFROMSTARTOUT1_OFST (0)
#define FRAMESFROMSTARTOUT1_MSK (0xffffffff << FRAMESFROMSTARTOUT1_OFST)
#define FRAMESFROMSTARTOUTREG2 (0x11C)
#define FRAMESFROMSTARTOUT2_OFST (0)
#define FRAMESFROMSTARTOUT2_MSK (0xffffffff << FRAMESFROMSTARTOUT2_OFST)
#define FRAMETIMEOUTREG1 (0x120)
#define FRAMETIMEOUT1_OFST (0)
#define FRAMETIMEOUT1_MSK (0xffffffff << FRAMETIMEOUT1_OFST)
#define FRAMETIMEOUTREG2 (0x124)
#define FRAMETIMEOUT2_OFST (0)
#define FRAMETIMEOUT2_MSK (0xffffffff << FRAMETIMEOUT2_OFST)
#define DELAYOUTREG1 (0x128)
#define DELAYOUT1_OFST (0)
#define DELAYOUT1_MSK (0xffffffff << DELAYOUT1_OFST)
#define DELAYOUTREG2 (0x12C)
#define DELAYOUT2_OFST (0)
#define DELAYOUT2_MSK (0xffffffff << DELAYOUT2_OFST)
#define CYCLESOUTREG1 (0x130)
#define CYCLESOUT1_OFST (0)
#define CYCLESOUT1_MSK (0xffffffff << CYCLESOUT1_OFST)
#define CYCLESOUTREG2 (0x134)
#define CYCLESOUT2_OFST (0)
#define CYCLESOUT2_MSK (0xffffffff << CYCLESOUT2_OFST)
#define FRAMESOUTREG1 (0x138)
#define FRAMESOUT1_OFST (0)
#define FRAMESOUT1_MSK (0xffffffff << FRAMESOUT1_OFST)
#define FRAMESOUTREG2 (0x13C)
#define FRAMESOUT2_OFST (0)
#define FRAMESOUT2_MSK (0xffffffff << FRAMESOUT2_OFST)
#define PERIODOUTREG1 (0x140)
#define PERIODOUT1_OFST (0)
#define PERIODOUT1_MSK (0xffffffff << PERIODOUT1_OFST)
#define PERIODOUTREG2 (0x144)
#define PERIODOUT2_OFST (0)
#define PERIODOUT2_MSK (0xffffffff << PERIODOUT2_OFST)
#define DELAYINREG1 (0x148)
#define DELAYIN1_OFST (0)
#define DELAYIN1_MSK (0xffffffff << DELAYIN1_OFST)
#define DELAYINREG2 (0x14C)
#define DELAYIN2_OFST (0)
#define DELAYIN2_MSK (0xffffffff << DELAYIN2_OFST)
#define CYCLESINREG1 (0x150)
#define CYCLESIN1_OFST (0)
#define CYCLESIN1_MSK (0xffffffff << CYCLESIN1_OFST)
#define CYCLESINREG2 (0x154)
#define CYCLESIN2_OFST (0)
#define CYCLESIN2_MSK (0xffffffff << CYCLESIN2_OFST)
#define FRAMESINREG1 (0x158)
#define FRAMESIN1_OFST (0)
#define FRAMESIN1_MSK (0xffffffff << FRAMESIN1_OFST)
#define FRAMESINREG2 (0x15C)
#define FRAMESIN2_OFST (0)
#define FRAMESIN2_MSK (0xffffffff << FRAMESIN2_OFST)
#define PERIODINREG1 (0x160)
#define PERIODIN1_OFST (0)
#define PERIODIN1_MSK (0xffffffff << PERIODIN1_OFST)
#define PERIODINREG2 (0x164)
#define PERIODIN2_OFST (0)
#define PERIODIN2_MSK (0xffffffff << PERIODIN2_OFST)
#define PATTERNOUTREG0 (0x200)
#define PATTERNOUT0_OFST (0)
#define PATTERNOUT0_MSK (0xffffffff << PATTERNOUT0_OFST)
#define PATTERNOUTREG1 (0x204)
#define PATTERNOUT1_OFST (0)
#define PATTERNOUT1_MSK (0xffffffff << PATTERNOUT1_OFST)
#define PATTERNINREG0 (0x208)
#define PATTERNIN0_OFST (0)
#define PATTERNIN0_MSK (0xffffffff << PATTERNIN0_OFST)
#define PATTERNINREG1 (0x20C)
#define PATTERNIN1_OFST (0)
#define PATTERNIN1_MSK (0xffffffff << PATTERNIN1_OFST)
#define PATTERNIOMASKREG0 (0x210)
#define PATTERNIOMASK0_OFST (0)
#define PATTERNIOMASK0_MSK (0xffffffff << PATTERNIOMASK0_OFST)
#define PATTERNIOMASKREG1 (0x214)
#define PATTERNIOMASK1_OFST (0)
#define PATTERNIOMASK1_MSK (0xffffffff << PATTERNIOMASK1_OFST)
#define PATTERNIOSETREG0 (0x218)
#define PATTERNIOSET0_OFST (0)
#define PATTERNIOSET0_MSK (0xffffffff << PATTERNIOSET0_OFST)
#define PATTERNIOSETREG1 (0x21C)
#define PATTERNIOSET1_OFST (0)
#define PATTERNIOSET1_MSK (0xffffffff << PATTERNIOSET1_OFST)
#define PATTERNCONTROLREG (0x220)
#define PATTERNWRBIT_OFST (0)
#define PATTERNWRBIT_MSK (0x00000001 << PATTERNWRBIT_OFST)
#define PATTERNRDBIT_OFST (1)
#define PATTERNRDBIT_MSK (0x00000001 << PATTERNRDBIT_OFST)
#define PATTERNADDRESSPTR_OFST (16)
#define PATTERNADDRESSPTR_MSK (0x00001fff << PATTERNADDRESSPTR_OFST)
#define PATTERNLIMITADDRESSREG (0x228)
#define PATTERNLIMITADDRESS_OFST (0)
#define PATTERNLIMITADDRESS_MSK (0xffffffff << PATTERNLIMITADDRESS_OFST)
#define PATTERNLOOP1ADDRESSREG (0x230)
#define PATTERNLOOP1ADDRESS_OFST (0)
#define PATTERNLOOP1ADDRESS_MSK (0xffffffff << PATTERNLOOP1ADDRESS_OFST)
#define PATTERNNLOOPS1REG (0x238)
#define PATTERNNLOOPS1_OFST (0)
#define PATTERNNLOOPS1_MSK (0xffffffff << PATTERNNLOOPS1_OFST)
#define PATTERNWAIT1ADDRESSREG (0x240)
#define PATTERNWAIT1ADDRESS_OFST (0)
#define PATTERNWAIT1ADDRESS_MSK (0xffffffff << PATTERNWAIT1ADDRESS_OFST)
#define PATTERNWAIT1TIMEREG1 (0x248)
#define PATTERNWAIT1TIME1_OFST (0)
#define PATTERNWAIT1TIME1_MSK (0xffffffff << PATTERNWAIT1TIME1_OFST)
#define PATTERNWAIT1TIMEREG2 (0x24C)
#define PATTERNWAIT1TIME2_OFST (0)
#define PATTERNWAIT1TIME2_MSK (0xffffffff << PATTERNWAIT1TIME2_OFST)
#define PATTERNLOOP2ADDRESSREG (0x250)
#define PATTERNLOOP2ADDRESS_OFST (0)
#define PATTERNLOOP2ADDRESS_MSK (0xffffffff << PATTERNLOOP2ADDRESS_OFST)
#define PATTERNNLOOPS2REG (0x258)
#define PATTERNNLOOPS2_OFST (0)
#define PATTERNNLOOPS2_MSK (0xffffffff << PATTERNNLOOPS2_OFST)
#define PATTERNWAIT2ADDRESSREG (0x260)
#define PATTERNWAIT2ADDRESS_OFST (0)
#define PATTERNWAIT2ADDRESS_MSK (0xffffffff << PATTERNWAIT2ADDRESS_OFST)
#define PATTERNWAIT2TIMEREG1 (0x268)
#define PATTERNWAIT2TIME1_OFST (0)
#define PATTERNWAIT2TIME1_MSK (0xffffffff << PATTERNWAIT2TIME1_OFST)
#define PATTERNWAIT2TIMEREG2 (0x26C)
#define PATTERNWAIT2TIME2_OFST (0)
#define PATTERNWAIT2TIME2_MSK (0xffffffff << PATTERNWAIT2TIME2_OFST)
#define PATTERNLOOP3ADDRESSREG (0x270)
#define PATTERNLOOP3ADDRESS_OFST (0)
#define PATTERNLOOP3ADDRESS_MSK (0xffffffff << PATTERNLOOP3ADDRESS_OFST)
#define PATTERNNLOOPS3REG (0x278)
#define PATTERNNLOOPS3_OFST (0)
#define PATTERNNLOOPS3_MSK (0xffffffff << PATTERNNLOOPS3_OFST)
#define PATTERNWAIT3ADDRESSREG (0x280)
#define PATTERNWAIT3ADDRESS_OFST (0)
#define PATTERNWAIT3ADDRESS_MSK (0xffffffff << PATTERNWAIT3ADDRESS_OFST)
#define PATTERNWAIT3TIMEREG1 (0x288)
#define PATTERNWAIT3TIME1_OFST (0)
#define PATTERNWAIT3TIME1_MSK (0xffffffff << PATTERNWAIT3TIME1_OFST)
#define PATTERNWAIT3TIMEREG2 (0x28C)
#define PATTERNWAIT3TIME2_OFST (0)
#define PATTERNWAIT3TIME2_MSK (0xffffffff << PATTERNWAIT3TIME2_OFST)
#define PATTERNLOOP4ADDRESSREG (0x290)
#define PATTERNLOOP4ADDRESS_OFST (0)
#define PATTERNLOOP4ADDRESS_MSK (0xffffffff << PATTERNLOOP4ADDRESS_OFST)
#define PATTERNNLOOPS4REG (0x298)
#define PATTERNNLOOPS4_OFST (0)
#define PATTERNNLOOPS4_MSK (0xffffffff << PATTERNNLOOPS4_OFST)
#define PATTERNWAIT4ADDRESSREG (0x300)
#define PATTERNWAIT4ADDRESS_OFST (0)
#define PATTERNWAIT4ADDRESS_MSK (0xffffffff << PATTERNWAIT4ADDRESS_OFST)
#define PATTERNWAIT4TIMEREG1 (0x308)
#define PATTERNWAI4TIME1_OFST (0)
#define PATTERNWAI4TIME1_MSK (0xffffffff << PATTERNWAI4TIME1_OFST)
#define PATTERNWAIT4TIMEREG2 (0x30C)
#define PATTERNWAIT4TIME2_OFST (0)
#define PATTERNWAIT4TIME2_MSK (0xffffffff << PATTERNWAIT4TIME2_OFST)
#define PATTERNLOOP5ADDRESSREG (0x310)
#define PATTERNLOOP5ADDRESS_OFST (0)
#define PATTERNLOOP5ADDRESS_MSK (0xffffffff << PATTERNLOOP5ADDRESS_OFST)
#define PATTERNNLOOPS5REG (0x318)
#define PATTERNNLOOPS5_OFST (0)
#define PATTERNNLOOPS5_MSK (0xffffffff << PATTERNNLOOPS5_OFST)
#define PATTERNWAIT5ADDRESSREG (0x320)
#define PATTERNWAIT5ADDRESS_OFST (0)
#define PATTERNWAIT5ADDRESS_MSK (0xffffffff << PATTERNWAIT5ADDRESS_OFST)
#define PATTERNWAIT5TIMEREG1 (0x328)
#define PATTERNWAIT5TIME1_OFST (0)
#define PATTERNWAIT5TIME1_MSK (0xffffffff << PATTERNWAIT5TIME1_OFST)
#define PATTERNWAIT5TIMEREG2 (0x32C)
#define PATTERNWAIT5TIME2_OFST (0)
#define PATTERNWAIT5TIME2_MSK (0xffffffff << PATTERNWAIT5TIME2_OFST)
#define PATTERNLOOP6ADDRESSREG (0x330)
#define PATTERNLOOP6ADDRESS_OFST (0)
#define PATTERNLOOP6ADDRESS_MSK (0xffffffff << PATTERNLOOP6ADDRESS_OFST)
#define PATTERNNLOOPS6REG (0x338)
#define PATTERNNLOOPS6_OFST (0)
#define PATTERNNLOOPS6_MSK (0xffffffff << PATTERNNLOOPS6_OFST)
#define PATTERNWAIT6ADDRESSREG (0x340)
#define PATTERNWAIT6ADDRESS_OFST (0)
#define PATTERNWAIT6ADDRESS_MSK (0xffffffff << PATTERNWAIT6ADDRESS_OFST)
#define PATTERNWAIT6TIMEREG1 (0x348)
#define PATTERNWAIT6TIME1_OFST (0)
#define PATTERNWAIT6TIME1_MSK (0xffffffff << PATTERNWAIT6TIME1_OFST)
#define PATTERNWAIT6TIMEREG2 (0x34C)
#define PATTERNWAIT6TIME2_OFST (0)
#define PATTERNWAIT6TIME2_MSK (0xffffffff << PATTERNWAIT6TIME2_OFST)
#define EXPCTRLREG (0x400)
#define STARTP_OFST (0)
#define STARTP_MSK (0x00000001 << STARTP_OFST)
#define EXPFRAMESREG (0x408)
#define NOFRAMES_OFST (0)
#define NOFRAMES_MSK (0xffffffff << NOFRAMES_OFST)
#define EXPTIMEREG (0x410)
#define EXPTIME_OFST (0)
#define EXPTIME_MSK (0xffffffff << EXPTIME_OFST)

View File

@ -1,211 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "slsDetectorFunctionList.h"
#include "arm64.h"
#include "clogger.h"
#include "common.h"
#include "sharedMemory.h"
#include "sls/versionAPI.h"
#include <string.h>
#include <unistd.h> // usleep
#include <arpa/inet.h> // INET_ADDRSTRLEN
// Global variable from slsDetectorServer_funcs
extern int debugflag;
extern int updateFlag;
extern const enum detectorType myDetectorType;
// Global variable from communication_funcs.c
extern int isControlServer;
int initError = OK;
int initCheckDone = 0;
char initErrorMessage[MAX_STR_LENGTH];
int detPos[2] = {0, 0};
int isInitCheckDone() { return initCheckDone; }
int getInitResult(char **mess) {
*mess = initErrorMessage;
return initError;
}
void basictests() {
initError = OK;
initCheckDone = 0;
memset(initErrorMessage, 0, MAX_STR_LENGTH);
#ifdef VIRTUAL
LOG(logINFOBLUE, ("****** Xilinx Chip Test Board Virtual Server ******\n"));
#else
LOG(logINFOBLUE, ("********** Xilinx Chip Test Board Server **********\n"));
#endif
if (mapCSP0() == FAIL) {
strcpy(initErrorMessage,
"Could not map to memory. Cannot proceed. Check Firmware.\n");
LOG(logERROR, (initErrorMessage));
initError = FAIL;
return;
}
#ifndef VIRTUAL
/*if ((!debugflag) && (!updateFlag) &&
((validateKernelVersion(KERNEL_DATE_VRSN) == FAIL) ||
(checkType() == FAIL) || (testFpga() == FAIL) ||
(testBus() == FAIL))) {*/
if ((!debugflag) && (!updateFlag) &&
((validateKernelVersion(KERNEL_DATE_VRSN) == FAIL) ||
(checkType() == FAIL) /*|| (testFpga() == FAIL) ||
(testBus() == FAIL)*/)) {
sprintf(initErrorMessage,
"Could not pass basic tests of FPGA and bus. Cannot proceed. "
"Check Firmware. (Firmware version:0x%lx) \n",
getFirmwareVersion());
LOG(logERROR, ("%s\n\n", initErrorMessage));
initError = FAIL;
return;
}
#endif
uint32_t ipadd = getDetectorIP();
uint64_t macadd = getDetectorMAC();
int64_t fwversion = getFirmwareVersion();
char swversion[MAX_STR_LENGTH] = {0};
memset(swversion, 0, MAX_STR_LENGTH);
getServerVersion(swversion);
uint32_t requiredFirmwareVersion = REQRD_FRMWRE_VRSN;
LOG(logINFOBLUE,
("**************************************************\n"
"Detector IP Addr:\t\t 0x%x\n"
"Detector MAC Addr:\t\t 0x%lx\n\n"
"Firmware Version:\t\t 0x%lx\n"
"Software Version:\t\t %s\n"
"Required Firmware Version:\t 0x%x\n"
"********************************************************\n",
ipadd, macadd, fwversion, swversion, requiredFirmwareVersion));
}
int checkType() {
#ifdef VIRTUAL
return OK;
#endif
u_int32_t type =
((bus_r(FPGAVERSIONREG) & DETTYPE_MSK) >> DETTYPE_OFST);
if (type != XILINX_CHIPTESTBOARD) {
LOG(logERROR,
("This is not a Xilinx CTB firmware (read %d, expected %d)\n", type,
XILINX_CHIPTESTBOARD));
return FAIL;
}
return OK;
}
/* Ids */
void getServerVersion(char *version) { strcpy(version, APIXILINXCTB); }
uint64_t getFirmwareVersion() {
#ifdef VIRTUAL
return REQRD_FRMWRE_VRSN;
#endif
return ((bus_r(FPGAVERSIONREG) & COMPDATE_MSK) >> COMPDATE_OFST);
}
u_int64_t getDetectorMAC() {
#ifdef VIRTUAL
return 0;
#else
char output[255], mac[255] = "";
u_int64_t res = 0;
FILE *sysFile =
popen("ifconfig eth0 | grep ether | awk '{ print $2 }'", "r");
fgets(output, sizeof(output), sysFile);
pclose(sysFile);
// getting rid of ":"
char *pch;
pch = strtok(output, ":");
while (pch != NULL) {
strcat(mac, pch);
pch = strtok(NULL, ":");
}
sscanf(mac, "%lx", &res);
return res;
#endif
}
u_int32_t getDetectorIP() {
#ifdef VIRTUAL
return 0;
#endif
char temp[INET_ADDRSTRLEN] = "";
u_int32_t res = 0;
// execute and get address
char output[255];
FILE *sysFile = popen(
"ifconfig | grep 'inet '| grep -v '127.0.0.1' | awk '{ print $2 }'",
"r");
fgets(output, sizeof(output), sysFile);
pclose(sysFile);
// converting IPaddress to hex.
char *pcword = strtok(output, ".");
while (pcword != NULL) {
sprintf(output, "%02x", atoi(pcword));
strcat(temp, output);
pcword = strtok(NULL, ".");
}
strcpy(output, temp);
sscanf(output, "%x", &res);
// LOG(logINFO, ("ip:%x\n",res);
return res;
}
/* initialization */
void initControlServer() {
if (!updateFlag && initError == OK) {
setupDetector();
}
initCheckDone = 1;
}
void initStopServer() {
if (!updateFlag && initError == OK) {
usleep(CTRL_SRVR_INIT_TIME_US);
if (mapCSP0() == FAIL) {
initError = FAIL;
strcpy(initErrorMessage,
"Stop Server: Map Fail. Cannot proceed. Check Firmware.\n");
LOG(logERROR, (initErrorMessage));
initCheckDone = 1;
return;
}
#ifdef VIRTUAL
sharedMemory_setStop(0);
#endif
}
initCheckDone = 1;
}
/* set up detector */
void setupDetector() {
LOG(logINFO, ("This Server is for 1 Xilinx Chip Test Board\n"));
#ifdef VIRTUAL
sharedMemory_setStatus(IDLE);
#endif
LOG(logINFO, ("Goodbye...\n"));
}
int setDetectorPosition(int pos[]) {
memcpy(detPos, pos, sizeof(detPos));
return OK;
}
int *getDetectorPosition() { return detPos; }
int getNumberofUDPInterfaces() { return 1; }

View File

@ -1,18 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#include "RegisterDefs.h"
#include "sls/sls_detector_defs.h"
#define REQRD_FRMWRE_VRSN (0x230000)
#define KERNEL_DATE_VRSN "Wed Nov 29 17:32:14 CET 2023"
#define LINKED_SERVER_NAME "xilinx_ctbDetectorServer"
#define CTRL_SRVR_INIT_TIME_US (2 * 1000 * 1000)
/* Hardware Definitions */
#define NCHAN (1)
enum ADCINDEX { V_PWR_IO };
enum DACINDEX { D0 };

View File

@ -4,13 +4,10 @@ set(SOURCES
src/DetectorImpl.cpp
src/Module.cpp
src/Detector.cpp
src/HelpDacs.cpp
src/CmdProxy.cpp
src/CmdParser.cpp
src/Pattern.cpp
src/CtbConfig.cpp
src/Caller.cpp
src/CallerSpecial.cpp
src/inferAction.cpp
)
add_library(slsDetectorObject OBJECT
@ -32,6 +29,7 @@ target_link_libraries(slsDetectorObject
rt
PRIVATE
slsProjectWarnings
"$<BUILD_INTERFACE:libzmq-static>"
)
set(DETECTOR_LIBRARY_TARGETS slsDetectorObject)
@ -79,30 +77,26 @@ endif()
if(SLS_USE_TEXTCLIENT)
set(det_bin_names "sls_detector_put"
# Loop over list to generate command line binaries
set(bin_names "sls_detector_put"
"sls_detector_get"
"sls_detector_acquire"
"sls_detector_help"
"sls_detector"
)
set(det_cmd_name "PUT" "GET" "READOUT" "HELP" "INFER")
list(LENGTH det_bin_names len1)
"sls_detector_help")
set(cmd_name "PUT" "GET" "READOUT" "HELP")
list(LENGTH bin_names len1)
math(EXPR len2 "${len1} - 1")
foreach(val RANGE ${len2})
list(GET det_bin_names ${val} val1)
list(GET det_cmd_name ${val} val2)
list(GET bin_names ${val} val1)
list(GET cmd_name ${val} val2)
message(STATUS "${val1} ${val2}")
add_executable(${val1} src/CmdApp.cpp)
add_executable(${val1} src/CmdLineApp.cpp)
target_link_libraries(${val1}
slsDetectorStatic
pthread
rt
slsDetectorStatic
pthread
rt
)
SET_SOURCE_FILES_PROPERTIES( src/Caller.cpp PROPERTIES COMPILE_FLAGS "-Wno-unused-variable -Wno-unused-but-set-variable")
set_target_properties(${val1} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
COMPILE_DEFINITIONS ${val2}=1
@ -111,8 +105,7 @@ if(SLS_USE_TEXTCLIENT)
set_property(TARGET ${val1} PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()
endforeach()
install(TARGETS ${det_bin_names} DESTINATION bin)
install(TARGETS ${bin_names} DESTINATION bin)
endif(SLS_USE_TEXTCLIENT)

View File

@ -1,10 +0,0 @@
#include "Caller.h"
#include "sls/logger.h"
#include "sls/string_utils.h"
#include <iostream>
namespace sls {
// THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE
}

View File

@ -1,88 +0,0 @@
// This file is used as input to generate the caller class
#include "CmdParser.h"
#include "HelpDacs.h"
#include "sls/Detector.h"
#include <iostream>
#include <string>
#include <vector>
namespace sls {
class Caller {
public:
Caller(Detector *ptr) : det(ptr) {}
void call(const std::string &command,
const std::vector<std::string> &arguments, int detector_id,
int action, std::ostream &os = std::cout, int receiver_id = -1);
IpAddr getDstIpFromAuto();
IpAddr getSrcIpFromAuto();
UdpDestination getUdpEntry();
void GetLevelAndUpdateArgIndex(int action,
std::string levelSeparatedCommand,
int &level, int &iArg, size_t nGetArgs,
size_t nPutArgs);
void WrongNumberOfParameters(size_t expected);
template <typename V> std::string OutStringHex(const V &value) {
if (value.equal())
return ToStringHex(value.front());
return ToStringHex(value);
}
template <typename V> std::string OutStringHex(const V &value, int width) {
if (value.equal())
return ToStringHex(value.front(), width);
return ToStringHex(value, width);
}
template <typename V> std::string OutString(const Result<V> &value) {
if (value.equal())
return ToString(value.front());
return ToString(value);
}
template <typename V> std::string OutString(const V &value) {
return ToString(value);
}
template <typename V>
std::string OutString(const V &value, const std::string &unit) {
if (value.equal())
return ToString(value.front(), unit);
return ToString(value, unit);
}
std::vector<std::string> getAllCommands();
std::string list(int action);
// THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (1)
std::vector<std::string> args;
std::string cmd;
Detector *det;
int det_id{-1};
int rx_id{-1};
private:
bool ReplaceIfDepreciated(std::string &command);
using FunctionMap = std::map<std::string, std::string (Caller::*)(int)>;
using StringMap = std::map<std::string, std::string>;
Detector *ptr; // pointer to the detector that executes the command
FunctionMap functions{
{"list", &Caller::list},
// THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (2)
};
StringMap depreciated_functions{
// THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (3)
};
};
} // namespace sls

View File

@ -1,236 +0,0 @@
import argparse
import json
from pathlib import Path
# command to generate the ast
# clang version: 14.0.0-1ubuntu1.1
# clang++ -Xclang -ast-dump=json -Xclang -ast-dump-filter -Xclang StringTo -c ToString.cpp -I ../include/ -std=gnu++11
#
import yaml
AUTOCOMPLETE_PATH = Path(__file__).parent
DUMP_PATH = AUTOCOMPLETE_PATH / 'dump.json'
FIXED_PATH = AUTOCOMPLETE_PATH / 'fixed.json'
type_values = {
'special::mv': ["mv", "mV"],
"special::deg": ["deg"],
"special::time_unit": ["s", "ms", "us", "ns"],
"special::hard": ["hard"],
"special::force-delete-normal-file": ["--force-delete-normal-file"],
"special::currentSourceFix": ["fix", "nofix"],
"special::currentSourceLow": ["normal", "low"],
"special::path": [],
"special::pedestal_parameters" : ["", "0"]
}
def get_types(arg_types):
ret = set()
for arg_type in arg_types:
if type_info(arg_type) == 'base':
if arg_type == 'bool':
ret = ret.union(["0", "1"])
else:
tmp = [not_list for not_list in type_values[arg_type] if not isinstance(not_list, list)]
ret = ret.union(tmp)
#Intercept the options and in case detector specific options appear replace the
#list of options with a command line call that fetches them
#TODO! Rename sls_detector_get
if "defs::dacIndex" in arg_types:
return "`sls_detector_get daclist | sed -e 's/.*\[\(.*\)\].*/\\1/' | sed 's/,//g'`"
elif "defs::detectorSettings" in arg_types:
return "`sls_detector_get settingslist | sed -e 's/.*\[\(.*\)\].*/\\1/' | sed 's/,//g'`"
elif "defs::timingMode" in arg_types:
return "`sls_detector_get timinglist | sed -e 's/.*\[\(.*\)\].*/\\1/' | sed 's/,//g'`"
return ret
def type_info(type_name):
if type_name.startswith('defs::') or type_name.startswith('slsDetectorDefs::'):
return 'enum'
if type_name.startswith('special::'):
return 'special'
return 'base'
def get_enum(function):
return function['type']['qualType'].split(' ')[0]
def get_literal(ifstmt):
stringliteral = []
expression = ifstmt['inner'][0]
if expression['kind'] == 'BinaryOperator':
if expression['opcode'] == '!=':
return None, None
for cxxOperatorCall in expression['inner']:
if cxxOperatorCall['kind'] == 'CXXOperatorCallExpr':
implicitCastExpr = cxxOperatorCall['inner'][2]
stringliteral.append(implicitCastExpr['inner'][0]['value'][1:-1])
else:
cxxOperatorCall = expression
implicitCastExpr = cxxOperatorCall['inner'][2]
stringliteral = implicitCastExpr['inner'][0]['value'][1:-1]
retstmt = get_object_by_kind(ifstmt['inner'], 'ReturnStmt')
declrefexpt = get_object_by_kind(retstmt['inner'], 'DeclRefExpr')
enum_val = declrefexpt["referencedDecl"]["name"]
return enum_val, stringliteral
def get_object_by_kind(inner, kind, position=1):
for obj in inner:
if obj['kind'] == kind:
position -= 1
if position == 0:
return obj
return None
def generate_type_values():
functions = json.loads(FIXED_PATH.read_text())
for function in functions:
if function['kind'] != 'FunctionDecl' or function['name'] != 'StringTo':
continue
enum = get_enum(function)
if not enum.startswith('defs::'):
continue
# if enum != 'defs::dacIndex':
# continue
if not function['loc']['file'].endswith('ToString.cpp'):
continue
compound_stmt = get_object_by_kind(function['inner'], 'CompoundStmt')
for ifstmt in compound_stmt['inner']:
if ifstmt['kind'] != 'IfStmt':
continue
enum_val, stringliteral = get_literal(ifstmt)
if enum_val is None:
continue
if enum not in type_values or type_values[enum] is None:
type_values[enum] = []
type_values[enum].append(stringliteral)
items = list(type_values.items())
for key, val in items:
if key.startswith('defs::'):
new_key = key.split('::')[1]
new_key = 'slsDetectorDefs::' + new_key
type_values[new_key] = val
elif key.startswith('slsDetectorDefs::'):
new_key = key.split('::')[1]
new_key = 'defs::' + new_key
type_values[new_key] = val
return json.dumps(type_values, indent=2)
def fix_json():
with DUMP_PATH.open('r') as f:
tmp = '[\n'
for line in f.read().split('\n'):
if line.startswith('}'):
tmp += line + ',\n'
else:
tmp += line + '\n'
tmp = tmp[:-3] + '\n]'
with FIXED_PATH.open('w') as f:
f.write(tmp)
def generate_bash_autocomplete(output_path=Path(__file__).parent / 'bash_autocomplete.sh', input_path=Path(__file__).parent / 'bash_autocomplete.in.sh'):
generate_type_values()
output_file = output_path.open('w')
template_file = input_path.open('r')
def writeline(line):
output_file.write(line + '\n')
class if_block:
def __init__(self, condition):
self.condition = condition
def __enter__(self):
output_file.write('if [[ ' + self.condition + ' ]]; then\n')
def __exit__(self, type, value, traceback):
output_file.write('fi\n')
class function:
def __init__(self, name):
self.name = name
def __enter__(self):
output_file.write(self.name + '() {\n')
def __exit__(self, type, value, traceback):
output_file.write('}\n')
command_path = Path(__file__).parent.parent / 'extended_commands.yaml'
commands = yaml.unsafe_load(command_path.open('r'))
for line in template_file:
if '-- THIS LINE WILL BE REPLACED WITH GENERATED CODE --' not in line:
output_file.write(line)
continue
writeline(f'local SLS_COMMANDS=" {" ".join(commands.keys())} "')
# generate functions
for command_name, command in commands.items():
# added for debugging
if command_name == 'xxxexptime':
continue
with function('__' + command_name):
writeline('FCN_RETURN=""')
actions = ['GET', 'PUT']
for action in actions:
if action in command['actions'] and 'args' in command['actions'][action]:
args = command['actions'][action]['args']
possible_argc = {}
for arg in args:
if arg['argc'] == 0:
pass
for i in range(arg['argc']):
if i + 1 not in possible_argc:
possible_argc[i + 1] = []
possible_argc[i + 1].append(arg['arg_types'][i])
if possible_argc:
with if_block(f'${{IS_GET}} -eq {"1" if action == "GET" else "0"}'):
for argc in possible_argc:
with if_block(f'"${{cword}}" == "{argc + 1}"'):
if "defs::detectorSettings" in possible_argc[argc]:
print(argc, command_name, possible_argc[argc])
choices = get_types(possible_argc[argc])
#check if we got choices back or a bash command
if isinstance(choices, (list,set)):
writeline(f'FCN_RETURN="{" ".join(sorted(choices))}"')
else:
writeline(f'FCN_RETURN="{choices}"')
if 'special::path' in possible_argc[argc]:
writeline('IS_PATH=1')
writeline('return 0')
output_file.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='use parsed c++ code to generate autocomplete snippets')
parser.add_argument('-f', '--fix', action='store_true', help='fix the parsed ast to make it loadable')
# parser.add_argument('-p', '--path', type=str, help='output path to the fixed ast', default='ast.json')
args = parser.parse_known_args()
if args[0].fix:
fix_json()
ret = generate_type_values()
print(ret)

View File

@ -1,167 +0,0 @@
# GENERATED FILE - DO NOT EDIT
# ANY CHANGES TO THIS FILE WILL BE OVERWRITTEN
_sd() {
# Taken from https://github.com/scop/bash-completion/blob/15b74b1050333f425877a7cbd99af2998b95c476/bash_completion#L770C12-L770C12
# Reassemble command line words, excluding specified characters from the
# list of word completion separators (COMP_WORDBREAKS).
# @param $1 chars Characters out of $COMP_WORDBREAKS which should
# NOT be considered word breaks. This is useful for things like scp where
# we want to return host:path and not only path, so we would pass the
# colon (:) as $1 here.
# @param $2 words Name of variable to return words to
# @param $3 cword Name of variable to return cword to
#
_comp__reassemble_words()
{
local exclude="" i j line ref
# Exclude word separator characters?
if [[ $1 ]]; then
# Yes, exclude word separator characters;
# Exclude only those characters, which were really included
exclude="[${1//[^$COMP_WORDBREAKS]/}]"
fi
# Default to cword unchanged
printf -v "$3" %s "$COMP_CWORD"
# Are characters excluded which were former included?
if [[ $exclude ]]; then
# Yes, list of word completion separators has shrunk;
line=$COMP_LINE
# Re-assemble words to complete
for ((i = 0, j = 0; i < ${#COMP_WORDS[@]}; i++, j++)); do
# Is current word not word 0 (the command itself) and is word not
# empty and is word made up of just word separator characters to
# be excluded and is current word not preceded by whitespace in
# original line?
while [[ $i -gt 0 && ${COMP_WORDS[i]} == +($exclude) ]]; do
# Is word separator not preceded by whitespace in original line
# and are we not going to append to word 0 (the command
# itself), then append to current word.
[[ $line != [[:blank:]]* ]] && ((j >= 2)) && ((j--))
# Append word separator to current or new word
ref="$2[$j]"
printf -v "$ref" %s "${!ref-}${COMP_WORDS[i]}"
# Indicate new cword
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
# Remove optional whitespace + word separator from line copy
line=${line#*"${COMP_WORDS[i]}"}
# Indicate next word if available, else end *both* while and
# for loop
if ((i < ${#COMP_WORDS[@]} - 1)); then
((i++))
else
break 2
fi
# Start new word if word separator in original line is
# followed by whitespace.
[[ $line == [[:blank:]]* ]] && ((j++))
done
# Append word to current word
ref="$2[$j]"
printf -v "$ref" %s "${!ref-}${COMP_WORDS[i]}"
# Remove optional whitespace + word from line copy
line=${line#*"${COMP_WORDS[i]}"}
# Indicate new cword
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
done
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
else
# No, list of word completions separators hasn't changed;
for i in "${!COMP_WORDS[@]}"; do
printf -v "$2[i]" %s "${COMP_WORDS[i]}"
done
fi
}
local FCN_RETURN=""
local IS_PATH=0
# -- THIS LINE WILL BE REPLACED WITH GENERATED CODE --
COMPREPLY=()
local OPTIONS_NEW=""
# check if bash or zsh
# _get_comp_words_by_ref is a bash built-in function, we check if it exists
declare -Ff _get_comp_words_by_ref > /dev/null && IS_BASH=1 || IS_BASH=0
# bash interprets the colon character : as a special character and splits the argument in two
# different than what zsh does
# https://stackoverflow.com/a/3224910
# https://stackoverflow.com/a/12495727
local cur
local cword words=()
_comp__reassemble_words ":" words cword
cur=${words[cword]}
# check the action (get or put)
case "${words[0]}" in
"sls_detector_get" | "g" | "detg")
local IS_GET=1
;;
*)
local IS_GET=0
;;
esac
# if no command is written, autocomplete with the commands
if [[ ${cword} -eq 1 ]]; then
# local SLS_COMMANDS="trimbits exptime"
local SLS_COMMANDS_NEW=""
case "$cur" in
[0-9]*:*)
local suggestions=($(compgen -W "${SLS_COMMANDS}" -- "${cur#*:}"))
COMPREPLY=( ${suggestions[*]} )
;;
[0-9]*)
COMPREPLY=()
;;
*)
COMPREPLY=( $( compgen -W "$SLS_COMMANDS -h" -- "$cur" ) );;
esac
return 0
fi
if [[ ${cword} -eq 2 ]] && [[ ${words[1]} == "-h" ]]; then
COMPREPLY=( $( compgen -W "$SLS_COMMANDS" -- "$cur" ) )
return 0
fi
# if a command is written, autocomplete with the options
# call the function for the command
if [[ "$SLS_COMMANDS" == *"${words[1]##*:}"* ]]; then
__"${words[1]##*:}"
fi
# if IS_PATH is activated, autocomplete with the path
if [[ ${IS_PATH} -eq 1 ]]; then
COMPREPLY=($(compgen -f -- "${cur}"))
return 0
fi
# autocomplete with the options
COMPREPLY=($(compgen -W "${FCN_RETURN}" -- "${cur}"))
}
complete -F _sd -o filenames sls_detector_get
complete -F _sd -o filenames g
complete -F _sd -o filenames detg
complete -F _sd -o filenames sls_detector_put
complete -F _sd -o filenames p
complete -F _sd -o filenames detp
complete -F _sd -o filenames sls_detector
complete -F _sd -o filenames det

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,177 +0,0 @@
#### simpler version of autocomplete.sh to understand the logic
#### each command has its own function when called it will produce the possible values for autocompletion
_sd() {
# Reassemble command line words, excluding specified characters from the
# list of word completion separators (COMP_WORDBREAKS).
# @param $1 chars Characters out of $COMP_WORDBREAKS which should
# NOT be considered word breaks. This is useful for things like scp where
# we want to return host:path and not only path, so we would pass the
# colon (:) as $1 here.
# @param $2 words Name of variable to return words to
# @param $3 cword Name of variable to return cword to
#
_comp__reassemble_words()
{
local exclude="" i j line ref
# Exclude word separator characters?
if [[ $1 ]]; then
# Yes, exclude word separator characters;
# Exclude only those characters, which were really included
exclude="[${1//[^$COMP_WORDBREAKS]/}]"
fi
# Default to cword unchanged
printf -v "$3" %s "$COMP_CWORD"
# Are characters excluded which were former included?
if [[ $exclude ]]; then
# Yes, list of word completion separators has shrunk;
line=$COMP_LINE
# Re-assemble words to complete
for ((i = 0, j = 0; i < ${#COMP_WORDS[@]}; i++, j++)); do
# Is current word not word 0 (the command itself) and is word not
# empty and is word made up of just word separator characters to
# be excluded and is current word not preceded by whitespace in
# original line?
while [[ $i -gt 0 && ${COMP_WORDS[i]} == +($exclude) ]]; do
# Is word separator not preceded by whitespace in original line
# and are we not going to append to word 0 (the command
# itself), then append to current word.
[[ $line != [[:blank:]]* ]] && ((j >= 2)) && ((j--))
# Append word separator to current or new word
ref="$2[$j]"
printf -v "$ref" %s "${!ref-}${COMP_WORDS[i]}"
# Indicate new cword
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
# Remove optional whitespace + word separator from line copy
line=${line#*"${COMP_WORDS[i]}"}
# Indicate next word if available, else end *both* while and
# for loop
if ((i < ${#COMP_WORDS[@]} - 1)); then
((i++))
else
break 2
fi
# Start new word if word separator in original line is
# followed by whitespace.
[[ $line == [[:blank:]]* ]] && ((j++))
done
# Append word to current word
ref="$2[$j]"
printf -v "$ref" %s "${!ref-}${COMP_WORDS[i]}"
# Remove optional whitespace + word from line copy
line=${line#*"${COMP_WORDS[i]}"}
# Indicate new cword
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
done
((i == COMP_CWORD)) && printf -v "$3" %s "$j"
else
# No, list of word completions separators hasn't changed;
for i in "${!COMP_WORDS[@]}"; do
printf -v "$2[i]" %s "${COMP_WORDS[i]}"
done
fi
}
__exptime(){
if [ "${IS_GET}" == "1" ]; then
if [ "${cword}" == "2" ]; then
FCN_RETURN="s ms us ns"
fi
else
if [ "${cword}" == "2" ]; then
FCN_RETURN=""
fi
if [ "${cword}" == "3" ]; then
FCN_RETURN="s ms us ns"
fi
fi
}
# trimbits will activate IS_PATH and signal that its input is a path
__trimbits(){
if [ "${IS_GET}" == "1" ]; then
if [ "${cword}" == "2" ]; then
FCN_RETURN=""
IS_PATH=1
fi
else
if [ "${cword}" == "2" ]; then
FCN_RETURN=""
IS_PATH=1
fi
fi
}
local cword words=()
_comp__reassemble_words ":" words cword
local FCN_RETURN=""
local IS_PATH=0
COMPREPLY=()
local OPTIONS_NEW=""
# _get_comp_words_by_ref -n : cur
local cur=${words[cword]}
# check the action (get or put)
if [ "${words[0]}" == "sls_detector_get" ]; then
local IS_GET=1
else
local IS_GET=0
fi
# if no command is written, autocomplete with the commands
if [[ ${cword} -eq 1 ]]; then
local SLS_COMMANDS="trimbits exptime"
local SLS_COMMANDS_NEW=""
case "$cur" in
[0-9]*:*)
local suggestions=($(compgen -W "${SLS_COMMANDS}" -- "${cur#*:}"))
COMPREPLY=( ${suggestions[*]} )
;;
[0-9]*)
COMPREPLY=()
;;
*)
COMPREPLY=( $( compgen -W "$SLS_COMMANDS -h" -- "$cur" ) );;
esac
return 0
fi
# if a command is written, autocomplete with the options
# call the function for the command
__"${words[1]##*:}"
# if IS_PATH is activated, autocomplete with the path
if [[ ${IS_PATH} -eq 1 ]]; then
COMPREPLY=($(compgen -f -- "${cur}"))
return 0
fi
# autocomplete with the options
COMPREPLY=($(compgen -W "${FCN_RETURN}" -- "${cur}"))
}
complete -F _sd -o filenames sls_detector_put
complete -F _sd -o filenames sls_detector_get
complete -F _sd -o filenames g
complete -F _sd -o filenames p
complete -F _sd -o filenames detg
complete -F _sd -o filenames detp
complete -F _sd -o filenames sls_detector
complete -F _sd -o filenames det

View File

@ -1,77 +0,0 @@
# GENERATED FILE - DO NOT EDIT
# ANY CHANGES TO THIS FILE WILL BE OVERWRITTEN
_sd() {
# -- THIS LINE WILL BE REPLACED WITH GENERATED CODE --
local FCN_RETURN=""
local IS_PATH=0
COMPREPLY=()
local OPTIONS_NEW=""
words=("${COMP_WORDS[@]}")
cword=$COMP_CWORD
local cur=${words[cword]}
# check the action (get or put)
case "${words[0]}" in
"sls_detector_get" | "g" | "detg")
local IS_GET=1
;;
*)
local IS_GET=0
;;
esac
# if no command is written, autocomplete with the commands
if [[ ${cword} -eq 1 ]]; then
case "$cur" in
[0-9]*)
for i in $SLS_COMMANDS; do
SLS_COMMANDS_NEW="${SLS_COMMANDS_NEW} ${cur%%:*}:$i"
done
COMPREPLY=( $( compgen -W "${SLS_COMMANDS_NEW}" -- "$cur" ) );;
*)
COMPREPLY=( $( compgen -W "$SLS_COMMANDS -h" -- "$cur" ) );;
esac
return 0
fi
if [[ ${cword} -eq 2 ]] && [[ ${words[1]} == "-h" ]]; then
COMPREPLY=( $( compgen -W "$SLS_COMMANDS" -- "$cur" ) )
return 0
fi
# if a command is written, autocomplete with the options
# call the function for the command
if [[ "$SLS_COMMANDS" == *"${words[1]##*:}"* ]]; then
__"${words[1]##*:}"
fi
# if IS_PATH is activated, autocomplete with the path
if [[ ${IS_PATH} -eq 1 ]]; then
COMPREPLY=($(compgen -f -- "${cur}"))
return 0
fi
# autocomplete with the options
COMPREPLY=($(compgen -W "${FCN_RETURN}" -- "${cur}"))
}
complete -F _sd -o filenames sls_detector_get
complete -F _sd -o filenames g
complete -F _sd -o filenames detg
complete -F _sd -o filenames sls_detector_put
complete -F _sd -o filenames p
complete -F _sd -o filenames detp
complete -F _sd -o filenames sls_detector
complete -F _sd -o filenames det

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,379 +0,0 @@
import copy
import logging
import yaml
from pathlib import Path
class CommandParser:
def __init__(
self,
commands_file: Path = Path(__file__).parent.parent / 'commands.yaml',
output_file: Path = Path(__file__).parent.parent / 'extended_commands.yaml'
):
self.output_file = output_file
self.commands_file = commands_file
self.fp = self.commands_file.open('r')
self.simple_commands = yaml.unsafe_load(self.fp)
self.extended_commands = {}
self.argc_set = set()
self.logger = logging.getLogger('command_parser')
self.__current_action: str = ''
FORMAT = '[%(levelname)s] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
self.propagate_config = {
'require_det_id': False,
'convert_det_id': True,
'input': [],
'input_types': [],
'function': '',
'output': [],
'cast_input': [],
'check_det_id': False,
'arg_types': [],
# 'store_result_in_t': False, # always true in GET action
}
self.default_config = {
'infer_action': True,
'help': '',
'actions': {}
}
def _verify_argument(self, arg, infer_action, command_name, action):
if arg['function'] == '' and 'ctb_output_list' not in arg:
special_exception_message_list = ["Cannot put", "Cannot get"]
if 'exceptions' in arg and arg['exceptions'][0]['condition'] == 'true' and any(ele in arg['exceptions'][0]['message'] for ele in special_exception_message_list):
self.logger.warning(f"{command_name} has a special exception message for {action}.")
else:
self.logger.warning(f"{command_name} [{action}] does not have a function")
if len(arg['input_types']) != len(arg['input']):
raise ValueError(f'Argument {arg} does not have the correct number of inputs')
if 'separate_time_units' in arg:
if arg['separate_time_units']['input'] == "":
raise ValueError(f'Argument {arg} does not have the correct number of inputs for separate_time_units')
if len(arg['separate_time_units']['output']) != 2:
raise ValueError(f'Argument {arg} does not have the correct number of outputs for separate_time_units')
if 'convert_to_time' in arg:
if len(arg['convert_to_time']['input']) != 2:
raise ValueError(f'Argument {arg} does not have the correct number of inputs for convert_to_time')
if len(arg['convert_to_time']['output']) == "":
raise ValueError(f'Argument {arg} does not have the correct number of outputs for convert_to_time')
# if infer_action:
# if arg['argc'] in self.argc_set:
# raise ValueError(f'Argument {arg} has a duplicate argc')
# self.argc_set.add(arg['argc'])
def verify_format(self):
# todo verify detectors
# todo verify circular inheritance
# todo verify child commands (those that inherit)
# todo verify that there is no wrongly typed parameters
# todo verify that the same number of input_types and input are given
# todo verify that each argument has argc (error can happen when inheriting)
for command_name, command in self.simple_commands.items():
if 'inherit_actions' in command or 'template' in command and command[
'template'] or 'is_description' in command and command['is_description']:
continue
self.argc_set = set()
if 'infer_action' not in command:
command['infer_action'] = True
if 'actions' not in command:
raise ValueError(f'Command {command_name} does not have any actions')
for action, action_params in command['actions'].items():
if 'argc' in action_params:
if 'args' in action_params:
raise ValueError(f'Action {action} has both argc and args')
arg = {**self.propagate_config, **action_params}
self._verify_argument(arg, command['infer_action'], command_name, action)
elif 'args' in action_params:
if type(action_params['args']) is not list:
raise ValueError(f'Action {action} args is not a list')
if len(action_params['args']) == 0:
raise ValueError(f'Action {action} args is empty')
action_args = {**self.propagate_config, **action_params}
del action_args['args']
for arg in action_params['args']:
arg = {**action_args, **arg}
self._verify_argument(arg, command['infer_action'], command_name, action)
self.logger.info('Commands file is valid ✅️')
return True
def _parse_inherited_command(self, parent, command, simple_parent):
"""
parse a command that inherits from parent command
:param parent: parsed parent command
:param command: the current command
:param simple_parent: unparsed parent command
:return: parsed command
"""
# deepcopy parent and command to avoid modifying the originals
command = copy.deepcopy(command)
config = copy.deepcopy(parent)
# add help
if 'help' in command:
config['help'] = command['help']
if 'actions' not in command:
return config
for action, command_params in command['actions'].items():
self.__current_action = action
if action not in config['actions']:
# todo: handle this case
pass
parent_params = config['actions'][action]
if 'args' in command_params:
# child has args => inherit action level params from parent + override with child args + use child's
# action level params
context = {**self.propagate_config, **simple_parent['actions'][action], **command_params}
config['actions'][action]['args'] = self.parse_action(context, command_params['args'])
elif 'argc' in command_params:
# child has action level args (argc)
context = {**self.propagate_config, **simple_parent['actions'][action], **command_params}
config['actions'][action]['args'] = self.parse_action(context, [])
else:
# child does not have args => use parent's action level params + override with child's action level
if 'args' in parent_params:
config['actions'][action]['args'] = self.parse_action({}, parent_params['args'], command_params)
if 'detectors' in command_params:
if command_params['detectors'] is None:
# if child has an empty detector section, then delete the parent's detector section
del config['actions'][action]['detectors']
continue
for detector_name, detector_params in command_params['detectors'].items():
if 'detectors' not in config['actions'][action]:
config['actions'][action]['detectors'] = {}
config_detector = config['actions'][action]['detectors']
if 'detectors' not in parent_params or detector_name not in parent_params['detectors']:
if 'args' in detector_params:
# if child has detector args and parent does not have detectors
# => use child's detector args
context = {**self.propagate_config, **simple_parent['actions'][action], **detector_params}
config_detector[detector_name] = self.parse_action(context, detector_params['args'])
elif 'args' in parent_params:
# if child does not have detector args and parent does not have detectors
# => use the child's action args
context = {**self.propagate_config, **simple_parent['actions'][action]}
config_detector[detector_name] = self.parse_action(context,
config['actions'][action]['args'],
detector_params)
elif detector_name in parent_params['detectors']:
if 'args' in detector_params:
# child and parent have the same detector and child has detector args
# => use child's detector args
context = {
**self.propagate_config,
**simple_parent['actions'][action],
**simple_parent['actions'][action]['detectors'][detector_name],
}
config_detector[detector_name] = self.parse_action(context, detector_params['args'])
else:
# child and parent have the same detector and child does not have detector args
# => use parent's detector args
priority_context = {**command_params, **detector_params}
config_detector[detector_name] = self.parse_action(
{},
parent_params['detectors'][detector_name],
priority_context
)
else:
pass
return config
def _parse_command(self, command):
"""
logic function for parse_command.
This function is recursive
:return: parsed command
"""
config = self.default_config.copy()
config.update(command)
config['actions'] = {}
# check if command inherits from another command
if 'inherit_actions' in command:
if command['inherit_actions'] in self.extended_commands:
# if parent command has already been parsed, use that
parent = self.extended_commands[command['inherit_actions']]
else:
# if parent command has not been parsed, parse it
parent = self.parse_command(command['inherit_actions'])
# parse the current command and merge it with the parent command
config = self._parse_inherited_command(parent, command, self.simple_commands[command['inherit_actions']])
return config
if 'actions' not in command:
return config
for action, action_params in command['actions'].items():
self.__current_action = action
config['actions'][action] = {}
config_action = config['actions'][action]
# the context in the current command and the current action
action_context = {**self.propagate_config, **action_params}
if 'args' not in action_params:
# parse the action with the action context
if action_params.keys() != {'detectors'}:
config_action['args'] = self.parse_action(action_context, [])
else:
config_action['args'] = self.parse_action(action_context, action_params['args'])
# check if the action has detectors
if 'detectors' in action_params:
config_action['detectors'] = {}
for detector_name, detector_params in action_params['detectors'].items():
# get the context for the detector and merge it with the action context
detector_context = {**action_context, **detector_params}
# if the detector does not have args, then use the action args
# otherwise, use the detector args and override the action args
tmp_args = []
if 'args' not in detector_params:
if 'args' in config_action:
tmp_args = config_action['args']
else:
tmp_args = detector_params['args']
detector_params['args'] = tmp_args
# parse the action with the detector context
config_action['detectors'][detector_name] = self.parse_action(detector_context,
tmp_args,
detector_params)
return config
def sanitize_argument(func):
def f(self, action_context, args_old, priority_context={}):
args = func(self, action_context, args_old, priority_context)
for i, arg in enumerate(args):
if 'args' in arg:
del arg['args']
if 'detectors' in arg:
del arg['detectors']
if not arg['cast_input']:
# if the cast_input is empty, then set it to False
arg['cast_input'] = [False] * len(arg['input'])
elif len(arg['cast_input']) != len(arg['input']):
# if the cast_input is not the same length as the input, then set it to False
arg['cast_input'] = [False] * len(arg['input'])
self.logger.warning(f'cast_input for {arg["function"]} '
f'with argc: {arg["argc"]} has different length than input')
if 'store_result_in_t' not in arg:
if self.__current_action == 'GET':
arg['store_result_in_t'] = True
else:
arg['store_result_in_t'] = False
return args
return f
@sanitize_argument
def parse_action(self, action_context, args, priority_context={}):
"""
parse an action
:param action_context: context of the action
:param args: arguments to be used in the action
:param priority_context: context that should override the arguments params
:return: parsed action
"""
def add_cast_input(argument):
return argument
# deepcopy action_context to avoid modifying the original
action_context = {**self.propagate_config, **copy.deepcopy(action_context)}
priority_context = copy.deepcopy(priority_context)
if 'detectors' in action_context:
del action_context['detectors']
if 'detectors' in priority_context:
del priority_context['detectors']
if args == []:
# if there are no arguments, then the action has only one argument
context = {**action_context, **priority_context}
return [add_cast_input(context)]
ret_args = []
if 'args' in action_context:
del action_context['args']
if 'args' in priority_context:
del priority_context['args']
# if there are arguments, then merge them with the action context and priority context
for arg in args:
arg = {**action_context, **arg, **priority_context}
ret_args.append(add_cast_input(arg))
return ret_args
def parse_command(self, command_name):
"""
parse a single command
This function is recursive
:param command_name: name of the command to parse
:return: the parsed command
"""
command = self.simple_commands[command_name]
parsed_command = self._parse_command(command)
if 'function_alias' not in command:
if 'command_name' in command:
parsed_command['function_alias'] = command['command_name']
else:
parsed_command['function_alias'] = command_name
if 'command_name' not in command:
parsed_command['command_name'] = command_name
if 'template' in command and command['template']:
return parsed_command
self.extended_commands[command_name] = parsed_command
return self.extended_commands[command_name]
def parse_all_commands(self):
"""
iterate over all commands in yaml file and parse them
:return: None
"""
for command_name in self.simple_commands:
# todo remove this (added for debugging)
if command_name != 'xtiming':
self.parse_command(command_name)
# post-process the parsed commands
self.post_process_all_commands()
yaml.Dumper.ignore_aliases = lambda *args: True
self.logger.info(f'parsed {len(self.extended_commands)} commands')
yaml.dump(self.extended_commands, self.output_file.open('w'), default_flow_style=False)
def post_process_all_commands(self):
for command_name, command in self.extended_commands.items():
if 'is_description' in command and command['is_description']:
continue
for action_name, action, in command['actions'].items():
for arg in action['args']:
if arg['argc'] == 0:
arg['arg_types'] = []
continue
if arg['argc'] == -1:
pass
if arg['arg_types'] == []:
arg['arg_types'] = arg['input_types']
# command_parser = CommandParser(Path(
# '/afs/psi.ch/user/b/braham_b/github/slsDetectorPackage/slsDetectorSoftware/generator/tests/command_parser/data/detectors.yaml'))
command_parser = CommandParser()
if __name__ == '__main__':
command_parser.verify_format()
command_parser.parse_all_commands()

View File

@ -1,282 +0,0 @@
class CodeGenerator:
def __init__(self):
self.file = None
self.actions_dict = {
'GET': 'slsDetectorDefs::GET_ACTION',
'PUT': 'slsDetectorDefs::PUT_ACTION',
'READOUT': 'slsDetectorDefs::READOUT_ACTION',
'HELP': 'slsDetectorDefs::HELP_ACTION',
}
self.template_file = None
def open(self, path):
self.file = path.open('w')
def close(self):
self.file.close()
self.file = None
def write_line(self, line):
self.file.write(line + '\n')
def write(self, text):
self.file.write(text)
def write_opening(self, path):
"""Write the opening file for the caller.cpp file"""
self.template_file = path.open('r')
for line in self.template_file:
if "THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE" in line:
return
self.file.write(line)
def write_closing(self):
"""Write the closing file for the caller.cpp file"""
for line in self.template_file.readlines():
self.file.write(line)
self.template_file.close()
def write_header(self, in_path, out_path, commands, deprecated_commands):
"""Write the header file for the caller.h file"""
with out_path.open('w') as fp:
with in_path.open('r') as fp2:
for line in fp2:
if "THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (1)" in line:
for command_name, command in commands.items():
if 'duplicate_function' in command and command['duplicate_function']:
continue
fp.write(f'std::string {command["function_alias"]}(int action);\n')
continue
if "THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (2)" in line:
map_string = ''
for command_name, command in commands.items():
map_string += f'{{"{command_name}", &Caller::{command["function_alias"]}}},'
fp.write(map_string[:-1] + '\n')
continue
if "THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (3)" in line:
for key, value in deprecated_commands.items():
fp.write(f'{{"{key}", "{value}"}},\n')
continue
fp.write(line)
def write_infer_header(self, in_path, out_path, commands):
"""Write the header file for the inferAction.h file"""
with out_path.open('w+') as fp:
with in_path.open('r') as fp2:
for line in fp2:
if "THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (1) - DO NOT REMOVE" in line:
for command_name, command in commands.items():
if 'duplicate_function' in command and command['duplicate_function']:
continue
fp.write(f'int {command["function_alias"]}();\n')
continue
if "THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (2) - DO NOT REMOVE" in line:
map_string = ''
for command_name, command in commands.items():
map_string += f'{{"{command_name}", &InferAction::{command["function_alias"]}}},'
fp.write(map_string[:-1] + '\n')
continue
fp.write(line)
def write_infer_cpp(self, in_path, out_path, commands, non_dist, type_dist):
"""Write the source file for the inferAction.cpp file"""
with in_path.open('r') as fp2:
for line in fp2:
if "THIS COMMENT TO BE REPLACED BY THE ACTUAL CODE (1) - DO NOT REMOVE" in line:
for command_name, command in commands.items():
if 'duplicate_function' in command and command['duplicate_function']:
continue
with function('int', f"InferAction::{command['function_alias']}", []) as f:
if (command_name, -1) in non_dist| type_dist:
self.write_line(
f'throw RuntimeError("sls_detector is disabled for command: {command_name}. Use sls_detector_get or sls_detector_put");')
elif not command['infer_action']:
self.write_line('throw RuntimeError("infer_action is disabled");')
else:
checked_argcs = set()
for action, action_params in command['actions'].items():
for arg in action_params['args']:
if arg['argc'] in checked_argcs:
continue
checked_argcs.add(arg['argc'])
with if_block(f'args.size() == {arg["argc"]}'):
# check if this argc is not distinguishable
if (command_name, arg["argc"]) in non_dist | type_dist:
self.write_line(
f'throw RuntimeError("sls_detector is disabled for command: {command_name} with number of arguments {arg["argc"]}. Use sls_detector_get or sls_detector_put");')
else:
self.write_line(f'return {self.actions_dict[action]};')
with else_block():
self.write_line(
'throw RuntimeError("Could not infer action: Wrong number of arguments");')
continue
self.write_line(line)
def write_check_arg(self):
pass
def write_arg(self, args, action, command_name):
for arg in args:
if arg['argc'] != -1:
if_block(f'args.size() == {arg["argc"]}',).__enter__()
if 'pattern_command' in arg and arg['pattern_command']:
self.write_line(f'int level = -1, iArg = 0, '
f'nGetArgs = {arg["pattern_command"]["nGetArgs"]},'
f' nPutArgs = {arg["pattern_command"]["nPutArgs"]};\nGetLevelAndUpdateArgIndex(action, '
f'"{arg["pattern_command"]["command_name"]}", level, iArg, nGetArgs,nPutArgs);'
)
if 'extra_variables' in arg:
for var in arg['extra_variables']:
codegen.write_line(f'{var["type"]} {var["name"]} = {var["value"]};')
if 'separate_time_units' in arg and arg['separate_time_units']:
self.write_line(f'std::string tmp_time({arg["separate_time_units"]["input"]});')
self.write_line(f'std::string {arg["separate_time_units"]["output"][1]}'
f' = RemoveUnit(tmp_time);')
self.write_line(f'auto {arg["separate_time_units"]["output"][0]} = '
f'StringTo < time::ns > (tmp_time,'
f' {arg["separate_time_units"]["output"][1]});')
if 'convert_to_time' in arg and arg['convert_to_time']:
self.write_line(f'auto {arg["convert_to_time"]["output"]} = '
f'StringTo < time::ns > ({", ".join(arg["convert_to_time"]["input"])});')
input_arguments = []
if 'exceptions' in arg:
for exception in arg['exceptions']:
self.write_line(f'if ({exception["condition"]}) {{ throw RuntimeError({exception["message"]}); }}')
if 'check_det_id' in arg and arg['check_det_id']:
self.write_line(
f'if (det_id != -1) {{ throw RuntimeError("Cannot execute {command_name} at module level"); }} '
)
# only used for 3 commands :(
if 'ctb_output_list' in arg:
self.write_line(f"""
std::string suffix = " {arg['ctb_output_list']['suffix']}";
auto t = det->{arg['ctb_output_list']['GETFCNLIST']}();""")
if arg['ctb_output_list']['GETFCNNAME'] != '':
self.write_line(f"""
auto names = det->{arg['ctb_output_list']['GETFCNNAME']}();
auto name_it = names.begin();""")
self.write_line("os << '[';")
with if_block(f't.size() > 0'):
self.write_line(f"""
auto it = t.cbegin();
os << ToString({arg['ctb_output_list']['printable_name']}) << ' ';
os << OutString(det->{arg['ctb_output_list']['GETFCN']}(*it++, std::vector<int>{{det_id}}))<< suffix;
while (it != t.cend()) {{
os << ", " << ToString({arg['ctb_output_list']['printable_name']}) << ' ';
os << OutString(det->{arg['ctb_output_list']['GETFCN']}(*it++, std::vector<int>{{det_id}}))<< suffix;
}}
""")
self.write_line('os << "]\\n";')
if arg['argc'] != -1:
if_block().__exit__()
return
for i in range(len(arg['input'])):
if arg['cast_input'][i]:
self.write_line(
f'auto arg{i} = StringTo<{arg["input_types"][i]}>({arg["input"][i]});')
input_arguments.append(f'arg{i}')
else:
input_arguments.append(arg["input"][i])
if 'require_det_id' in arg and arg['require_det_id']:
if 'convert_det_id' in arg and arg['convert_det_id']:
input_arguments.append("std::vector<int>{ det_id }")
else:
input_arguments.append("det_id")
input_arguments = ", ".join(input_arguments)
# call function
if arg["function"]:
if arg['store_result_in_t']:
self.write_line(f'auto t = det->{arg["function"]}({input_arguments});')
else:
self.write_line(f'det->{arg["function"]}({input_arguments});')
else:
pass #We have no function so skip block
output_args = []
for output in arg['output']:
output_args.append(output)
if len(output_args) > 0:
self.write_line(f"os << {'<< '.join(output_args)} << '\\n';")
if arg['argc'] != -1:
if_block().__exit__()
class if_block:
def __init__(self, condition="", elseif=False):
self.condition = condition
self.elseif = elseif
self.block = False
def __enter__(self):
if self.elseif:
codegen.write_line('else if (' + self.condition + ') {')
else:
codegen.write_line('if (' + self.condition + ') {')
if self.block:
codegen.write_line('{\n')
def __exit__(self, *args):
codegen.write_line('}')
if self.block:
codegen.write_line('}')
codegen.write_line('')
class else_block:
def __init__(self):
pass
def __enter__(self):
codegen.write_line('else {')
codegen.write_line('')
def __exit__(self, *args):
codegen.write_line('}')
codegen.write_line('')
class for_block:
def __init__(self, condition):
self.condition = condition
def __enter__(self):
codegen.write_line('for (' + self.condition + ') {')
codegen.write_line('')
def __exit__(self, *args):
codegen.write_line('}')
codegen.write_line('')
class function:
def __init__(self, return_type, name, args: list[tuple[str, str]]):
self.name = name
self.args = args
self.return_type = return_type
def __enter__(self):
s = ""
for arg in self.args:
arg_type, arg_name = arg
s += arg_type + ' ' + arg_name + ', '
s = s[:-2]
codegen.write_line(self.return_type + ' ' + self.name +
f'({s}) {{')
codegen.write_line('')
return self
def __exit__(self, *args):
codegen.write_line('}')
codegen.write_line('')
codegen = CodeGenerator()

View File

@ -1,176 +0,0 @@
#configuration
detectorversion: firmwareversion
softwareversion: detectorserverversion
receiverversion: rx_version
detectornumber: serialnumber
thisversion: clientversion
detsizechan: detsize
trimdir: settingspath
settingsdir: settingspath
flippeddatax: fliprows
#acquisition parameters
cycles: triggers
cyclesl: triggersl
clkdivider: readoutspeed
speed: readoutspeed
vhighvoltage: highvoltage
digitest: imagetest
filter: filterresistor
readnlines: readnrows
# temperature
# super old dacs
vtr: vtrim
vrf: vrpreamp
vrs: vrshaper
vcall: vcal
vis: vishaper
vshaper: vrshaper
vpreamp: vrpreamp
vshaperneg: vrshaper_n
viinsh: vishaper
vpl: vcal_n
vph: vcal_p
# dacs
vthreshold: dac
vsvp: dac
vsvn: dac
vtrim: dac
vrpreamp: dac
vrshaper: dac
vtgstv: dac
vcmp_ll: dac
vcmp_lr: dac
vcal: dac
vcmp_rl: dac
vcmp_rr: dac
rxb_rb: dac
rxb_lb: dac
vcp: dac
vcn: dac
vishaper: dac
iodelay: dac
vref_ds: dac
vcascn_pb: dac
vcascp_pb: dac
vout_cm: dac
vcasc_out: dac
vin_cm: dac
vref_comp: dac
ib_test_c: dac
vrshaper_n: dac
vipre: dac
vdcsh: dac
vth1: dac
vth2: dac
vth3: dac
vcal_n: dac
vcal_p: dac
vcassh: dac
vcas: dac
vicin: dac
vipre_out: dac
vref_h_adc: dac
vb_comp_fe: dac
vb_comp_adc: dac
vcom_cds: dac
vref_rstore: dac
vb_opa_1st: dac
vref_comp_fe: dac
vcom_adc1: dac
vref_prech: dac
vref_l_adc: dac
vref_cds: dac
vb_cs: dac
vb_opa_fd: dac
vcom_adc2: dac
vb_ds: dac
vb_comp: dac
vb_pixbuf: dac
vin_com: dac
vdd_prot: dac
vbp_colbuf: dac
vb_sda: dac
vcasc_sfp: dac
vipre_cds: dac
ibias_sfp: dac
defaultdacs: resetdacs
#acquisition
busy: clearbusy
receiver: rx_status
framescaught: rx_framescaught
startingfnum: nextframenumber
#Network Configuration (Detector<->Receiver)
detectorip: udp_srcip
detectorip2: udp_srcip2
detectormac: udp_srcmac
detectormac2: udp_srcmac2
rx_udpip: udp_dstip
rx_udpip2: udp_dstip2
rx_udpmac: udp_dstmac
rx_udpmac2: udp_dstmac2
rx_udpport: udp_dstport
rx_udpport2: udp_dstport2
flowcontrol_10g: flowcontrol10g
txndelay_frame: txdelay_frame
txndelay_left: txdelay_left
txndelay_right: txdelay_right
#Receiver Config
r_silent: rx_silent
r_discardpolicy: rx_discardpolicy
r_padding: rx_padding
r_lock: rx_lock
r_lastclient: rx_lastclient
#File
fileformat: fformat
outdir: fpath
index: findex
enablefwrite: fwrite
masterfile: fmaster
overwrite: foverwrite
r_framesperfile: rx_framesperfile
#ZMQ Streaming Parameters (Receiver<->Client)
r_readfreq: rx_zmqfreq
rx_readfreq: rx_zmqfreq
rx_datastream: rx_zmqstream
#Eiger Specific
resmat: partialreset
#Jungfrau Specific
storagecells: extrastoragecells
auto_comp_disable: autocompdisable
comp_disable_time: compdisabletime
#Gotthard Specific
#Gotthard2 Specific
#Mythen3 Specific
#CTB Specific
adc: slowadc
flags: romode
i_a: im_a
i_b: im_b
i_c: im_c
i_d: im_d
i_io: im_io
#Pattern
#Moench
#Advanced
copydetectorserver: updatedetectorserver
#Insignificant
nframes: framecounter
now: runtime
timestamp: frametime
frameindex: rx_frameindex

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