Compare commits

..

60 Commits

Author SHA1 Message Date
a0c222b3c6 constructor 2020-01-20 14:23:28 +01:00
66b837eb59 Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2020-01-16 16:57:12 +01:00
6170c42618 explicit also in MacAddr 2020-01-16 16:57:04 +01:00
69dd5f3b5e Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2020-01-16 16:37:44 +01:00
c1fac7cdb7 fixed conversion for IpAddr 2020-01-16 16:31:11 +01:00
de57146e1b Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2020-01-16 16:14:11 +01:00
fb75986c55 mythne3: counters fixed 2020-01-16 16:13:40 +01:00
f3598c1f39 nullptr 2020-01-16 14:17:57 +01:00
9ac08ad5c9 clang-tidy header include order 2020-01-16 14:00:43 +01:00
bcb4942793 cleaning 2020-01-16 12:26:22 +01:00
4b69ac5cfc const string& in exceptions constructor 2020-01-16 11:44:01 +01:00
7a00732fa8 various minor things from clang-tidy 2020-01-16 11:39:35 +01:00
30a4a1740f added Mythen3 2020-01-15 17:56:08 +01:00
39ec29c0e6 added counters to python 2020-01-15 17:26:07 +01:00
de53747ddd Counters (#71)
* mythen3: adding counters mask, firmware still takes only number of counters for now

* mythen3: checking if module attached before powering on chip

* bug fix: loop inital declaration not allowed in c

* fix scope eiger test

* mythen3: renamed setCounters to setCounterMask and getCounterMask in API

* mythen3 replacing counting bits with popcount

Co-authored-by: Erik Fröjdh <erik.frojdh@gmail.com>
2020-01-14 17:40:46 +01:00
70c54f4315 added jungfrau again 2020-01-13 18:26:24 +01:00
a709384fbb renamed python detector 2020-01-13 16:33:02 +01:00
a1abd7587c Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2020-01-13 16:13:52 +01:00
8c8d213b56 python funcs 2020-01-13 16:13:47 +01:00
7b31fbc002 eiger virtual server bug fix: increasing subdeadtime 2020-01-13 14:18:43 +01:00
db9aa7589a tests fix 2020-01-13 12:07:30 +01:00
28f8a76dcc updated binaries 2020-01-10 09:05:26 +01:00
dac5ecd123 dbit 2020-01-08 16:44:42 +01:00
71b0ed271e CTB 2020-01-08 15:33:28 +01:00
c223f00511 Eiger 2020-01-08 14:55:16 +01:00
639ed52d65 pybind 2.4 2020-01-07 16:30:59 +01:00
6943763e3d Updated pybind11 to 2.4.3 2020-01-07 16:30:12 +01:00
4b3b518401 asamples dsamples 2020-01-07 16:18:36 +01:00
7379b1e2ef added python3.8 2020-01-07 15:48:38 +01:00
ed2a69744b Auto generating Python bindings (#70)
Auto generating python bindings
2020-01-07 15:47:38 +01:00
086cbacd84 mythen3: connected busy signal insttead of timer 2019-12-10 11:03:27 +01:00
af9b25fd67 eiger: validate trimval range 2019-12-10 10:32:28 +01:00
504fc2d095 ctb: validate asampes and dsamples > 0 for romode; client: exception caught in acquire to stop receiver and clear busy flag 2019-12-10 10:25:14 +01:00
5cf1502287 ctb bug fix: 10g adc enable mask 2019-12-09 11:30:54 +01:00
8881542156 ctb bug fix: clkioctrl not taken in hex 2019-12-05 17:15:31 +01:00
d9ae9a8cc6 eiger test 2019-12-05 11:00:55 +01:00
6765eb0c94 Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2019-12-04 10:25:25 +01:00
be3d82b7b4 format 2019-12-04 10:25:17 +01:00
4e0d1fa711 ctb rxr for pawel: updated packetsize to 8192 (datasize to 8144) 2019-12-03 17:25:39 +01:00
619106e05f eiger tests 2019-12-03 11:47:49 +01:00
9bc60518d8 Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2019-12-03 10:12:58 +01:00
12d168a6ef const strref 2019-12-03 10:12:47 +01:00
1a8337540a rxr: switched to threads for threadObject (from pthread), moved priorities to threadObject, mutex 2019-11-29 16:19:02 +01:00
16bec25b0c rxr: pthread to thread and created and destroyed tcp thread in constructor and destructor 2019-11-29 15:17:41 +01:00
f178b0da39 Merge branch 'rxr' into developer 2019-11-29 11:10:05 +01:00
2ece6b945e rxr: warnings shouldnt throw exception 2019-11-29 11:09:41 +01:00
1d6be74ee5 rxr: removed return ok or fail and replaced with exceptions 2019-11-29 10:29:36 +01:00
07455bb11e Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2019-11-27 18:42:27 +01:00
f4cdd759b0 clang-tidy 2019-11-27 18:42:16 +01:00
796890d1c8 Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2019-11-27 18:25:14 +01:00
3486137de3 bfin warnings fixed 2019-11-27 18:22:33 +01:00
d53082c615 clang-tidy empty() 2019-11-27 18:15:55 +01:00
c94f6a2bf2 Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2019-11-27 17:56:02 +01:00
2364364697 minor 2019-11-27 17:55:50 +01:00
ad0fb44573 Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2019-11-27 17:29:26 +01:00
9455a5fba1 ctb: adcenable10g included, 10g readout enables included 2019-11-27 17:28:57 +01:00
a28fa66e54 renamed CmdLineParser to CmdParser 2019-11-27 13:56:14 +01:00
e996068328 more tests 2019-11-27 13:39:06 +01:00
1bbd77536c Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer 2019-11-27 11:35:16 +01:00
ace105a268 more tests 2019-11-27 11:35:00 +01:00
109 changed files with 4548 additions and 3879 deletions

View File

@ -16,7 +16,8 @@ Checks: '*,
-hicpp-braces-around-statements,
-google-runtime-references,
-google-readability-todo,
-google-readability-braces-around-statements'
-google-readability-braces-around-statements,
-modernize-use-trailing-return-type'
HeaderFilterRegex: \.h
AnalyzeTemporaryDtors: false

View File

@ -8,6 +8,7 @@ env:
matrix:
- CONDA_PY=3.6
- CONDA_PY=3.7
- CONDA_PY=3.8
dist: trusty

View File

@ -1,7 +1,6 @@
cmake_minimum_required(VERSION 3.11)
project(slsDetectorPackage)
set(PROJECT_VERSION 5.0.0)
include(CheckIPOSupported)
@ -106,10 +105,10 @@ endif()
if(SLS_USE_SANITIZER)
# target_compile_options(slsProjectOptions INTERFACE -fsanitize=address,undefined -fno-omit-frame-pointer)
# target_link_libraries(slsProjectOptions INTERFACE -fsanitize=address,undefined)
target_compile_options(slsProjectOptions INTERFACE -fsanitize=thread)
target_link_libraries(slsProjectOptions INTERFACE -fsanitize=thread)
target_compile_options(slsProjectOptions INTERFACE -fsanitize=address,undefined -fno-omit-frame-pointer)
target_link_libraries(slsProjectOptions INTERFACE -fsanitize=address,undefined)
# target_compile_options(slsProjectOptions INTERFACE -fsanitize=thread)
# target_link_libraries(slsProjectOptions INTERFACE -fsanitize=thread)
endif()
#rapidjson

View File

@ -65,10 +65,10 @@ outputs:
- setuptools
- sls_detector_lib
- pyzmq
- pybind11 2.2
- pybind11 2.4
host:
- python
- pybind11 2.2
- pybind11 2.4
- pyzmq
- sls_detector_lib
- libstdcxx-ng

View File

@ -17,13 +17,13 @@
/*! \file document.h */
#include "reader.h"
#include "encodedstream.h"
#include "internal/meta.h"
#include "internal/strfunc.h"
#include "memorystream.h"
#include "encodedstream.h"
#include <new> // placement new
#include "reader.h"
#include <limits>
#include <new> // placement new
RAPIDJSON_DIAG_PUSH
#ifdef _MSC_VER

View File

@ -15,8 +15,8 @@
#ifndef RAPIDJSON_ENCODEDSTREAM_H_
#define RAPIDJSON_ENCODEDSTREAM_H_
#include "stream.h"
#include "memorystream.h"
#include "stream.h"
#ifdef __GNUC__
RAPIDJSON_DIAG_PUSH

View File

@ -15,9 +15,9 @@
#ifndef RAPIDJSON_STRTOD_
#define RAPIDJSON_STRTOD_
#include "ieee754.h"
#include "biginteger.h"
#include "diyfp.h"
#include "ieee754.h"
#include "pow10.h"
RAPIDJSON_NAMESPACE_BEGIN

View File

@ -164,8 +164,8 @@
#include "msinttypes/inttypes.h"
#else
// Other compilers should have this.
#include <stdint.h>
#include <inttypes.h>
#include <stdint.h>
#endif
//!@endcond
#ifdef RAPIDJSON_DOXYGEN_RUNNING

View File

@ -18,11 +18,11 @@
/*! \file reader.h */
#include "allocators.h"
#include "stream.h"
#include "encodedstream.h"
#include "internal/meta.h"
#include "internal/stack.h"
#include "internal/strtod.h"
#include "stream.h"
#include <limits>
#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)

View File

@ -2,7 +2,8 @@
pybind11_add_module(_sls_detector
src/main.cpp
src/enums.cpp
src/experimental.cpp
src/detector.cpp
src/network.cpp
)
target_link_libraries(_sls_detector PUBLIC
@ -24,12 +25,12 @@ set( PYTHON_FILES
dacs.py
decorators.py
detector_property.py
# detector.py
# eiger.py
detector.py
eiger.py
errors.py
experimental.py
# jungfrau_ctb.py
# jungfrau.py
ctb.py
jungfrau.py
mythen3.py
registers.py
utils.py

View File

@ -2,9 +2,14 @@ import os
import sys
import numpy as np
sys.path.append(os.path.join(os.getcwd(), 'bin'))
# from sls_detector import Eiger, Jungfrau, Detector, defs
from sls_detector import Detector
from sls_detector import Detector, Mythen3, Eiger, Jungfrau, DetectorDacs, Dac, Ctb
from sls_detector import dacIndex
d = Detector()
# e = Eiger()
# c = Ctb()
# j = Jungfrau()
m = Mythen3()

View File

@ -0,0 +1,25 @@
import subprocess
import locale
out = subprocess.run(['g', 'list'], stdout = subprocess.PIPE, encoding=locale.getpreferredencoding())
cmd = out.stdout.splitlines()
cmd.pop(0)
from sls_detector import Detector, Eiger, Ctb
pycmd = dir(Detector)+dir(Eiger)+dir(Ctb)
pycmd += ['vrf', 'vtr', 'vrs', 'vtgstv', 'vsvn', 'vtrim',
'vsvp', 'vth1', 'vth2', 'vth3', 'vshaper', 'vshaperneg', 'rxb_rb',
'rxb_lb', 'vref_prech', 'vref_restore', 'vref_cds',
'vpreamp', 'vref_comp', 'vref_comp_fe vref_ds', 'vref_h_adc',
'vref_l_adc', 'iodelay', 'list', 'vref_ds', 'vis', 'vpl',
'vref_comp_fe', 'vph', 'vout_cm', 'vcp', 'vcn', 'vcmp_ll', 'vcmp_lr'
, 'vcmp_rl', 'vcmp_rr']
missing = []
for c in cmd:
if c not in pycmd:
print(c)
missing.append(c)
print(f'Missing: {len(missing)} commands')

View File

@ -0,0 +1,84 @@
"""
This file is used to auto generate Python bindings for the
sls::Detector class. The tool needs the libclang bindings
to be installed.
When the Detector API is updated this file should be run
manually
"""
from clang import cindex
import subprocess
import argparse
from parse import system_include_paths
default_build_path = "/home/l_frojdh/sls/build/"
fpath = "../../slsDetectorSoftware/src/Detector.cpp"
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--build_path", help="Path to the build database", type = str, default=default_build_path)
cargs = parser.parse_args()
db = cindex.CompilationDatabase.fromDirectory(cargs.build_path)
index = cindex.Index.create()
args = db.getCompileCommands(fpath)
args = list(iter(args).__next__().arguments)[0:-1]
args = args + "-x c++ --std=c++11".split()
syspath = system_include_paths('clang++')
incargs = ["-I" + inc for inc in syspath]
args = args + incargs
tu = index.parse(fpath, args=args)
m = []
ag = []
lines = []
def get_arguments(node):
args = [a.type.spelling for a in node.get_arguments()]
args = [
"py::arg() = Positions{}" if item == "sls::Positions" else "py::arg()"
for item in args
]
args = ', '.join(args)
if args:
args = f', {args}'
return args
def visit(node):
if node.kind == cindex.CursorKind.CLASS_DECL:
if node.displayname == "Detector":
for child in node.get_children():
if (
child.kind == cindex.CursorKind.CXX_METHOD
and child.access_specifier == cindex.AccessSpecifier.PUBLIC
):
m.append(child)
args = get_arguments(child)
lines.append(f'.def(\"{child.spelling}\", &Detector::{child.spelling}{args})')
for child in node.get_children():
visit(child)
visit(tu.cursor)
with open('../src/detector_in.cpp') as f:
data = f.read()
s = ''.join(lines)
s += ';'
text = data.replace('[[FUNCTIONS]]', s)
warning = '/* WARINING This file is auto generated any edits might be overwritten without warning */\n\n'
with open('../src/detector.cpp', 'w') as f:
f.write(warning)
f.write(text)
# run clang format on the output
subprocess.run(['clang-format', '../src/detector.cpp', '-i'])

View File

@ -1,4 +1,9 @@
import re
import subprocess
from subprocess import PIPE
import os
def remove_comments(text):
def replacer(match):
s = match.group(0)
@ -10,4 +15,42 @@ def remove_comments(text):
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE
)
return re.sub(pattern, replacer, text)
return re.sub(pattern, replacer, text)
#based on ccsyspath: https://github.com/AndrewWalker/ccsyspath
def compiler_preprocessor_verbose(compiler, extraflags):
"""Capture the compiler preprocessor stage in verbose mode
"""
lines = []
with open(os.devnull, 'r', encoding='utf-8') as devnull:
cmd = [compiler, '-E']
cmd += extraflags
cmd += ['-', '-v']
p = subprocess.Popen(cmd, stdin=devnull, stdout=PIPE, stderr=PIPE)
p.wait()
lines = p.stderr.read()
lines = lines.splitlines()
return lines
def system_include_paths(compiler, cpp=True):
extraflags = []
if cpp:
extraflags = b'-x c++'.split()
lines = compiler_preprocessor_verbose(compiler, extraflags)
lines = [ line.strip() for line in lines ]
start = lines.index(b'#include <...> search starts here:')
end = lines.index(b'End of search list.')
lines = lines[start+1:end]
paths = []
for line in lines:
line = line.replace(b'(framework directory)', b'')
line = line.strip()
paths.append(line)
paths = [p.decode('utf-8') for p in paths]
return paths

View File

@ -38,7 +38,8 @@ ext_modules = [
'_sls_detector',
['src/main.cpp',
'src/enums.cpp',
'src/experimental.cpp'],
'src/detector.cpp',
'src/network.cpp'],
include_dirs=[
# Path to pybind11 headers
get_pybind_include(),

View File

@ -1,8 +1,10 @@
# from .detector import Detector, DetectorError, free_shared_memory
# from .eiger import Eiger
from .experimental import Detector
# from .jungfrau import Jungfrau
from .eiger import Eiger
from .ctb import Ctb
from .dacs import DetectorDacs, Dac
from .detector import Detector
from .jungfrau import Jungfrau
from .mythen3 import Mythen3
# from .jungfrau_ctb import JungfrauCTB
# from _sls_detector import DetectorApi
@ -15,3 +17,6 @@ timingMode = _sls_detector.slsDetectorDefs.timingMode
dacIndex = _sls_detector.slsDetectorDefs.dacIndex
detectorType = _sls_detector.slsDetectorDefs.detectorType
detectorSettings = _sls_detector.slsDetectorDefs.detectorSettings
IpAddr = _sls_detector.IpAddr
MacAddr = _sls_detector.MacAddr

121
python/sls_detector/ctb.py Normal file
View File

@ -0,0 +1,121 @@
from .detector import Detector
from .utils import element_if_equal
from .dacs import DetectorDacs
import _sls_detector
dacIndex = _sls_detector.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty
class CtbDacs(DetectorDacs):
"""
Ctb dacs
"""
_dacs = [('dac0', dacIndex(0), 0, 4000, 1400),
('dac1', dacIndex(1), 0, 4000, 1200),
('dac2', dacIndex(2), 0, 4000, 900),
('dac3', dacIndex(3), 0, 4000, 1050),
('dac4', dacIndex(4), 0, 4000, 1400),
('dac5', dacIndex(5), 0, 4000, 655),
('dac6', dacIndex(6), 0, 4000, 2000),
('dac7', dacIndex(7), 0, 4000, 1400),
('dac8', dacIndex(8), 0, 4000, 850),
('dac9', dacIndex(9), 0, 4000, 2000),
('dac10', dacIndex(10), 0, 4000, 2294),
('dac11', dacIndex(11), 0, 4000, 983),
('dac12', dacIndex(12), 0, 4000, 1475),
('dac13', dacIndex(13), 0, 4000, 1200),
('dac14', dacIndex(14), 0, 4000, 1600),
('dac15', dacIndex(15), 0, 4000, 1455),
('dac16', dacIndex(16), 0, 4000, 0),
('dac17', dacIndex(17), 0, 4000, 1000),
]
_dacnames = [_d[0] for _d in _dacs]
from .utils import element
class Ctb(Detector):
def __init__(self, id = 0):
super().__init__(id)
self._frozen = False
self._dacs = CtbDacs(self)
@property
def dacs(self):
return self._dacs
@property
@element
def v_a(self):
return self.getDAC(dacIndex.V_POWER_A, True)
@v_a.setter
def v_a(self, value):
self.setDAC(dacIndex.V_POWER_A, value, True)
@property
@element
def v_b(self):
return self.getDAC(dacIndex.V_POWER_B, True)
@v_b.setter
def v_b(self, value):
self.setDAC(dacIndex.V_POWER_B, value, True)
@property
@element
def v_c(self):
return self.getDAC(dacIndex.V_POWER_C, True)
@v_c.setter
def v_c(self, value):
self.setDAC(dacIndex.V_POWER_C, value, True)
@property
@element
def v_d(self):
return self.getDAC(dacIndex.V_POWER_D, True)
@v_d.setter
def v_d(self, value):
self.setDAC(dacIndex.V_POWER_D, value, True)
@property
@element
def v_io(self):
return self.getDAC(dacIndex.V_POWER_IO, True)
@v_io.setter
def v_io(self, value):
self.setDAC(dacIndex.V_POWER_IO, value, True)
@property
@element
def v_limit(self):
return self.getDAC(dacIndex.V_LIMIT, True)
@v_limit.setter
def v_limit(self, value):
self.setDAC(dacIndex.V_LIMIT, value, True)
@property
@element
def im_a(self):
return self.getMeasuredCurrent(dacIndex.I_POWER_A)
@property
@element
def im_b(self):
return self.getMeasuredCurrent(dacIndex.I_POWER_B)
@property
@element
def im_c(self):
return self.getMeasuredCurrent(dacIndex.I_POWER_C)
@property
@element
def im_d(self):
return self.getMeasuredCurrent(dacIndex.I_POWER_D)
@property
@element
def im_io(self):
return self.getMeasuredCurrent(dacIndex.I_POWER_IO)

View File

@ -1,7 +1,9 @@
from .detector_property import DetectorProperty
from functools import partial
import numpy as np
import _sls_detector
from .detector import freeze
dacIndex = _sls_detector.slsDetectorDefs.dacIndex
class Dac(DetectorProperty):
"""
This class represents a dac on the detector. One instance handles all
@ -14,11 +16,11 @@ class Dac(DetectorProperty):
"""
def __init__(self, name, low, high, default, detector):
def __init__(self, name, enum, low, high, default, detector):
super().__init__(partial(detector._api.getDac, name),
partial(detector._api.setDac, name),
detector._api.getNumberOfDetectors,
super().__init__(partial(detector.getDAC, enum, False),
lambda x, y : detector.setDAC(enum, x, False, y),
detector.size,
name)
self.min_value = low
@ -29,30 +31,16 @@ class Dac(DetectorProperty):
def __repr__(self):
"""String representation for a single dac in all modules"""
r_str = ['{:10s}: '.format(self.__name__)]
r_str += ['{:5d}, '.format(self.get(i)) for i in range(self.get_nmod())]
return ''.join(r_str).strip(', ')
dacstr = ''.join([f'{item:5d}' for item in self.get()])
return f'{self.__name__:10s}:{dacstr}'
# a = Dac('vrf', dacIndex.VRF, 0, 4000, 2500, d )
# @freeze
class DetectorDacs:
_dacs = [('vsvp', 0, 4000, 0),
('vtr', 0, 4000, 2500),
('vrf', 0, 4000, 3300),
('vrs', 0, 4000, 1400),
('vsvn', 0, 4000, 4000),
('vtgstv', 0, 4000, 2556),
('vcmp_ll', 0, 4000, 1500),
('vcmp_lr', 0, 4000, 1500),
('vcall', 0, 4000, 4000),
('vcmp_rl', 0, 4000, 1500),
('rxb_rb', 0, 4000, 1100),
('rxb_lb', 0, 4000, 1100),
('vcmp_rr', 0, 4000, 1500),
('vcp', 0, 4000, 200),
('vcn', 0, 4000, 2000),
('vis', 0, 4000, 1550),
('iodelay', 0, 4000, 660)]
_dacs = []
_dacnames = [_d[0] for _d in _dacs]
_allowed_attr = ['_detector', '_current']
_frozen = False
def __init__(self, detector):
# We need to at least initially know which detector we are connected to
@ -65,6 +53,8 @@ class DetectorDacs:
for _d in self._dacs:
setattr(self, '_'+_d[0], Dac(*_d, detector))
self._frozen = True
def __getattr__(self, name):
return self.__getattribute__('_' + name)
@ -73,8 +63,11 @@ class DetectorDacs:
if name in self._dacnames:
return self.__getattribute__('_' + name).__setitem__(slice(None, None, None), value)
else:
if self._frozen == True and name not in self._allowed_attr:
raise AttributeError(f'Dac not found: {name}')
super().__setattr__(name, value)
def __next__(self):
if self._current >= len(self._dacs):
self._current = 0
@ -95,7 +88,7 @@ class DetectorDacs:
"""
Read the dacs into a numpy array with dimensions [ndacs, nmodules]
"""
dac_array = np.zeros((len(self._dacs), self._detector.n_modules))
dac_array = np.zeros((len(self._dacs), len(self._detector)))
for i, _d in enumerate(self):
dac_array[i,:] = _d[:]
return dac_array
@ -115,11 +108,3 @@ class DetectorDacs:
for _d in self:
_d[:] = _d.default
def update_nmod(self):
"""
Update the cached value of nmod, needs to be run after adding or
removing detectors
"""
for _d in self:
_d._n_modules = self._detector.n_modules

View File

@ -5,33 +5,34 @@ runStatus = slsDetectorDefs.runStatus
speedLevel = slsDetectorDefs.speedLevel
dacIndex = slsDetectorDefs.dacIndex
from .utils import element_if_equal, all_equal
from .utils import element_if_equal, all_equal, get_set_bits, list_to_bitmask
from .utils import Geometry, to_geo
from .registers import Register, Adc_register
import datetime as dt
from functools import wraps
from collections import namedtuple
class Register:
"""
Helper class to read and write to registers using a
more Pythonic syntax
"""
def __init__(self, detector):
self._detector = detector
# class Register:
# """
# Helper class to read and write to registers using a
# more Pythonic syntax
# """
# def __init__(self, detector):
# self._detector = detector
def __getitem__(self, key):
return self._detector.readRegister(key)
# def __getitem__(self, key):
# return self._detector.readRegister(key)
def __setitem__(self, key, value):
self._detector.writeRegister(key, value)
# def __setitem__(self, key, value):
# self._detector.writeRegister(key, value)
def freeze(cls):
cls.__frozen = False
cls._frozen = False
def frozensetattr(self, key, value):
if self.__frozen and not hasattr(self, key):
if self._frozen and not hasattr(self, key):
raise AttributeError(
"Class {} is frozen. Cannot set {} = {}".format(
cls.__name__, key, value
@ -44,7 +45,7 @@ def freeze(cls):
@wraps(func)
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
self.__frozen = True
self._frozen = True
return wrapper
@ -69,6 +70,9 @@ class Detector(CppDetectorApi):
"""
super().__init__(multi_id)
self._register = Register(self)
self._adc_register = Adc_register(self)
# CONFIGURATION
def __len__(self):
@ -197,6 +201,18 @@ class Detector(CppDetectorApi):
else:
self.setSubExptime(dt.timedelta(seconds=t))
@property
def subdeadtime(self):
res = self.getSubDeadTime()
return element_if_equal([it.total_seconds() for it in res])
@subdeadtime.setter
def subdeadtime(self, t):
if isinstance(t, dt.timedelta):
self.setSubDeadTime(t)
else:
self.setSubDeadTime(dt.timedelta(seconds=t))
@property
def period(self):
@ -215,12 +231,8 @@ class Detector(CppDetectorApi):
# Time
#TODO! Rename to rx_framescaught
@property
def framescaught(self):
def rx_framescaught(self):
return element_if_equal(self.getFramesCaught())
@ -232,14 +244,7 @@ class Detector(CppDetectorApi):
def startingfnum(self, value):
self.setStartingFrameNumber(value)
#TODO! testing switches on automatically?
@property
def flowcontrol_10g(self):
return element_if_equal(self.getTenGigaFlowControl())
@flowcontrol_10g.setter
def flowcontrol_10g(self, enable):
self.setTenGigaFlowControl(enable)
#TODO! add txdelay
@ -459,6 +464,22 @@ class Detector(CppDetectorApi):
self.getDestinationUDPMAC2(mac)
@property
def udp_srcip(self):
return element_if_equal(self.getSourceUDPIP())
@udp_srcip.setter
def udp_srcip(self, ip):
self.setSourceUDPIP(ip)
@property
def udp_srcip2(self):
return element_if_equal(self.getSourceUDPIP2())
@udp_srcip2.setter
def udp_srcip2(self, ip):
self.setSourceUDPIP2(ip)
@property
def udp_dstport(self):
return element_if_equal(self.getDestinationUDPPort())
@ -582,6 +603,19 @@ class Detector(CppDetectorApi):
def reg(self):
return self._register
@property
def adcreg(self):
return self._adc_register
@property
def led(self):
return element_if_equal(self.getLEDEnable())
@led.setter
def led(self, value):
self.setLEDEnable(value)
@property
def ratecorr(self):
""" tau in ns """
@ -631,3 +665,183 @@ class Detector(CppDetectorApi):
@property
def vthreshold(self):
return element_if_equal(self.getDAC(dacIndex.THRESHOLD))
@property
def type(self):
return element_if_equal(self.getDetectorType())
@property
def rx_frameindex(self):
return element_if_equal(self.getRxCurrentFrameIndex())
@property
def rx_missingpackets(self):
return element_if_equal(self.getNumMissingPackets())
"""
Some Eiger stuff, does this have to be here or can we move it to subclass?
"""
@property
def partialreset(self):
return element_if_equal(self.getPartialReset())
@partialreset.setter
def partialreset(self, value):
self.setPartialReset(value)
@property
def tengiga(self):
return element_if_equal(self.getTenGiga())
@tengiga.setter
def tengiga(self, value):
self.setTenGiga(value)
@property
def overflow(self):
return element_if_equal(self.getOverFlowMode())
@overflow.setter
def overflow(self, value):
self.setOverFlowMode(value)
@property
def flowcontrol10g(self):
return element_if_equal(self.getTenGigaFlowControl())
@flowcontrol10g.setter
def flowcontrol10g(self, enable):
self.setTenGigaFlowControl(enable)
@property
def interruptsubframe(self):
return element_if_equal(self.getInterruptSubframe())
@interruptsubframe.setter
def interruptsubframe(self, value):
self.setInterruptSubframe(value)
@property
def gappixels(self):
return element_if_equal(self.getRxAddGapPixels())
@gappixels.setter
def gappixels(self, value):
self.setRxAddGapPixels(value)
@property
def measuredperiod(self):
res = self.getMeasuredPeriod()
return element_if_equal([it.total_seconds() for it in res])
@property
def measuredsubperiod(self):
res = self.getMeasuredSubFramePeriod()
return element_if_equal([it.total_seconds() for it in res])
@property
def storeinram(self):
return element_if_equal(self.getStoreInRamMode())
@storeinram.setter
def storeinram(self, value):
self.setStoreInRamMode(value)
"""
Mythen3 specific
"""
@property
def counters(self):
mask = self.getCounterMask()
mask = element_if_equal(mask)
if type(mask) == int:
return get_set_bits(mask)
else:
return [get_set_bits(m) for m in mask]
@counters.setter
def counters(self, values):
self.setCounterMask(list_to_bitmask(values))
"""
CTB stuff
"""
@property
def asamples(self):
return element_if_equal(self.getNumberOfAnalogSamples())
@asamples.setter
def asamples(self, N):
self.setNumberOfAnalogSamples(N)
@property
def dsamples(self):
return element_if_equal(self.getNumberOfDigitalSamples())
@dsamples.setter
def dsamples(self, N):
self.setNumberOfDigitalSamples(N)
@property
def dbitphase(self):
return element_if_equal(self.getDBITPhase())
@dbitphase.setter
def dbitphase(self, value):
self.setDBITPhase(value)
@property
def dbitclk(self):
return element_if_equal(self.getDBITClock())
@dbitclk.setter
def dbitclk(self, value):
self.setDBITClock(value)
@property
def dbitpipeline(self):
return element_if_equal(self.getDBITPipeline())
@dbitpipeline.setter
def dbitpipeline(self, value):
self.setDBITPipeline(value)
@property
def maxdbitphaseshift(self):
return element_if_equal(self.getMaxDBITPhaseShift())
@property
def rx_dbitlist(self):
return element_if_equal(self.getRxDbitList())
@rx_dbitlist.setter
def rx_dbitlist(self, value):
self.setRxDbitList(value)
@property
def rx_dbitoffset(self):
return element_if_equal(self.getRxDbitOffset())
@rx_dbitoffset.setter
def rx_dbitoffset(self, value):
self.setRxDbitOffset(value)
@property
def maxadcphaseshift(self):
return element_if_equal(self.getMaxADCPhaseShift())
@property
def maxclkphaseshift(self):
return element_if_equal(self.getMaxClockPhaseShift())
@property
def adcphase(self):
return element_if_equal()

View File

@ -14,21 +14,20 @@ class DetectorProperty:
def __getitem__(self, key):
if key == slice(None, None, None):
return [self.get(i) for i in range(self.get_nmod())]
return self.get()
elif isinstance(key, Iterable):
return [self.get(k) for k in key]
return self.get(list(key))
else:
return self.get(key)
return self.get([key])[0] #No list for single value
def __setitem__(self, key, value):
#operate on all values
if key == slice(None, None, None):
if isinstance(value, (np.integer, int)):
for i in range(self.get_nmod()):
self.set(i, value)
self.set(value, [])
elif isinstance(value, Iterable):
for i in range(self.get_nmod()):
self.set(i, value[i])
self.set(value[i], [i])
else:
raise ValueError('Value should be int or np.integer not', type(value))
@ -36,15 +35,14 @@ class DetectorProperty:
elif isinstance(key, Iterable):
if isinstance(value, Iterable):
for k,v in zip(key, value):
self.set(k,v)
self.set(v, [k])
elif isinstance(value, int):
for k in key:
self.set(k, value)
self.set(value, list(key))
#Set single value
elif isinstance(key, int):
self.set(key, value)
self.set(value, [key])
def __repr__(self):
s = ', '.join(str(v) for v in self[:])

View File

@ -6,17 +6,16 @@ Created on Wed Dec 6 11:51:18 2017
@author: l_frojdh
"""
import socket
from collections.abc import Iterable
from collections import namedtuple
from functools import partial
from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs
from .detector import Detector
# from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs
import _sls_detector
dacIndex = _sls_detector.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty
from .utils import element_if_equal
from sls_detector.errors import DetectorValueError, DetectorError
# from .utils import element_if_equal
# from sls_detector.errors import DetectorValueError, DetectorError
class EigerVcmp:
"""
@ -30,20 +29,20 @@ class EigerVcmp:
"""
def __init__(self, detector):
_names = ['vcmp_ll',
'vcmp_lr',
'vcmp_rl',
'vcmp_rr']
_dacs = [ dacIndex.VCMP_LL,
dacIndex.VCMP_LR,
dacIndex.VCMP_RL,
dacIndex.VCMP_RR]
self.set = []
self.get = []
for i in range(detector.n_modules):
for i in range(detector.size()):
if i % 2 == 0:
name = _names
dacs = _dacs
else:
name = _names[::-1]
for n in name:
self.set.append(partial(detector._api.setDac, n, i))
self.get.append(partial(detector._api.getDac, n, i))
dacs = _dacs[::-1]
for d in dacs:
self.set.append(lambda x, d=d, i=i : detector.setDAC(d, x, False, [i]))
self.get.append(lambda d=d, i=i : detector.getDAC(d, False, [i])[0])
def __getitem__(self, key):
if key == slice(None, None, None):
@ -58,80 +57,84 @@ class EigerVcmp:
class EigerDacs(DetectorDacs):
_dacs = [('vsvp', 0, 4000, 0),
('vtr', 0, 4000, 2500),
('vrf', 0, 4000, 3300),
('vrs', 0, 4000, 1400),
('vsvn', 0, 4000, 4000),
('vtgstv', 0, 4000, 2556),
('vcmp_ll', 0, 4000, 1500),
('vcmp_lr', 0, 4000, 1500),
('vcall', 0, 4000, 4000),
('vcmp_rl', 0, 4000, 1500),
('rxb_rb', 0, 4000, 1100),
('rxb_lb', 0, 4000, 1100),
('vcmp_rr', 0, 4000, 1500),
('vcp', 0, 4000, 200),
('vcn', 0, 4000, 2000),
('vis', 0, 4000, 1550),
('iodelay', 0, 4000, 660)]
"""
Eiger specific dacs
"""
_dacs = [('vsvp', dacIndex.SVP,0, 4000, 0),
('vtr', dacIndex.VTR,0, 4000, 2500),
('vrf', dacIndex.VRF,0, 4000, 3300),
('vrs', dacIndex.VRS,0, 4000, 1400),
('vsvn', dacIndex.SVN,0, 4000, 4000),
('vtgstv', dacIndex.VTGSTV,0, 4000, 2556),
('vcmp_ll', dacIndex.VCMP_LL,0, 4000, 1500),
('vcmp_lr', dacIndex.VCMP_LR,0, 4000, 1500),
('vcall', dacIndex.CAL,0, 4000, 4000),
('vcmp_rl', dacIndex.VCMP_RL,0, 4000, 1500),
('rxb_rb', dacIndex.RXB_RB,0, 4000, 1100),
('rxb_lb', dacIndex.RXB_LB,0, 4000, 1100),
('vcmp_rr', dacIndex.VCMP_RR,0, 4000, 1500),
('vcp', dacIndex.VCP,0, 4000, 200),
('vcn', dacIndex.VCN,0, 4000, 2000),
('vis', dacIndex.VIS,0, 4000, 1550),
('iodelay', dacIndex.IO_DELAY,0, 4000, 660)]
_dacnames = [_d[0] for _d in _dacs]
# # noinspection PyProtectedMember
# class DetectorDelays:
# _delaynames = ['frame', 'left', 'right']
# noinspection PyProtectedMember
class DetectorDelays:
_delaynames = ['frame', 'left', 'right']
def __init__(self, detector):
# We need to at least initially know which detector we are connected to
self._detector = detector
# def __init__(self, detector):
# # We need to at least initially know which detector we are connected to
# self._detector = detector
setattr(self, '_frame', DetectorProperty(detector._api.getDelayFrame,
detector._api.setDelayFrame,
detector._api.getNumberOfDetectors,
'frame'))
# setattr(self, '_frame', DetectorProperty(detector._api.getDelayFrame,
# detector._api.setDelayFrame,
# detector._api.getNumberOfDetectors,
# 'frame'))
setattr(self, '_left', DetectorProperty(detector._api.getDelayLeft,
detector._api.setDelayLeft,
detector._api.getNumberOfDetectors,
'left'))
# setattr(self, '_left', DetectorProperty(detector._api.getDelayLeft,
# detector._api.setDelayLeft,
# detector._api.getNumberOfDetectors,
# 'left'))
setattr(self, '_right', DetectorProperty(detector._api.getDelayRight,
detector._api.setDelayRight,
detector._api.getNumberOfDetectors,
'right'))
# Index to support iteration
self._current = 0
# setattr(self, '_right', DetectorProperty(detector._api.getDelayRight,
# detector._api.setDelayRight,
# detector._api.getNumberOfDetectors,
# 'right'))
# # Index to support iteration
# self._current = 0
def __getattr__(self, name):
return self.__getattribute__('_' + name)
# def __getattr__(self, name):
# return self.__getattribute__('_' + name)
def __setattr__(self, name, value):
if name in self._delaynames:
return self.__getattribute__('_' + name).__setitem__(slice(None, None, None), value)
else:
super().__setattr__(name, value)
# def __setattr__(self, name, value):
# if name in self._delaynames:
# return self.__getattribute__('_' + name).__setitem__(slice(None, None, None), value)
# else:
# super().__setattr__(name, value)
def __next__(self):
if self._current >= len(self._delaynames):
self._current = 0
raise StopIteration
else:
self._current += 1
return self.__getattr__(self._delaynames[self._current-1])
# def __next__(self):
# if self._current >= len(self._delaynames):
# self._current = 0
# raise StopIteration
# else:
# self._current += 1
# return self.__getattr__(self._delaynames[self._current-1])
def __iter__(self):
return self
# def __iter__(self):
# return self
def __repr__(self):
hn = self._detector.hostname
r_str = ['Transmission delay [ns]\n'
'{:11s}{:>8s}{:>8s}{:>8s}'.format('', 'left', 'right', 'frame')]
for i in range(self._detector.n_modules):
r_str.append('{:2d}:{:8s}{:>8d}{:>8d}{:>8d}'.format(i, hn[i], self.left[i], self.right[i], self.frame[i]))
return '\n'.join(r_str)
# def __repr__(self):
# hn = self._detector.hostname
# r_str = ['Transmission delay [ns]\n'
# '{:11s}{:>8s}{:>8s}{:>8s}'.format('', 'left', 'right', 'frame')]
# for i in range(self._detector.n_modules):
# r_str.append('{:2d}:{:8s}{:>8d}{:>8d}{:>8d}'.format(i, hn[i], self.left[i], self.right[i], self.frame[i]))
# return '\n'.join(r_str)
from .detector import freeze
@freeze
class Eiger(Detector):
"""
Subclassing Detector to set up correct dacs and detector specific
@ -145,79 +148,80 @@ class Eiger(Detector):
def __init__(self, id=0):
super().__init__(id)
self._active = DetectorProperty(self._api.getActive,
self._api.setActive,
self._api.getNumberOfDetectors,
'active')
self._vcmp = EigerVcmp(self)
self._frozen = False
self._dacs = EigerDacs(self)
self._trimbit_limits = namedtuple('trimbit_limits', ['min', 'max'])(0, 63)
self._delay = DetectorDelays(self)
# Eiger specific adcs
self._temp = DetectorAdcs()
self._temp.fpga = Adc('temp_fpga', self)
self._temp.fpgaext = Adc('temp_fpgaext', self)
self._temp.t10ge = Adc('temp_10ge', self)
self._temp.dcdc = Adc('temp_dcdc', self)
self._temp.sodl = Adc('temp_sodl', self)
self._temp.sodr = Adc('temp_sodr', self)
self._temp.fpgafl = Adc('temp_fpgafl', self)
self._temp.fpgafr = Adc('temp_fpgafr', self)
self._vcmp = EigerVcmp(self)
@property
def active(self):
"""
Is the detector active? Can be used to enable or disable a detector
module
# self._active = DetectorProperty(self.getActive,
# self.setActive,
# self.size,
# 'active')
# self._trimbit_limits = namedtuple('trimbit_limits', ['min', 'max'])(0, 63)
# self._delay = DetectorDelays(self)
Examples
----------
# # Eiger specific adcs
# self._temp = DetectorAdcs()
# self._temp.fpga = Adc('temp_fpga', self)
# self._temp.fpgaext = Adc('temp_fpgaext', self)
# self._temp.t10ge = Adc('temp_10ge', self)
# self._temp.dcdc = Adc('temp_dcdc', self)
# self._temp.sodl = Adc('temp_sodl', self)
# self._temp.sodr = Adc('temp_sodr', self)
# self._temp.fpgafl = Adc('temp_fpgafl', self)
# self._temp.fpgafr = Adc('temp_fpgafr', self)
# @property
# def active(self):
# """
# Is the detector active? Can be used to enable or disable a detector
# module
::
# Examples
# ----------
# ::
d.active
>> active: [True, True]
# d.active
# >> active: [True, True]
d.active[1] = False
>> active: [True, False]
"""
return self._active
# d.active[1] = False
# >> active: [True, False]
# """
# return self._active
@active.setter
def active(self, value):
self._active[:] = value
# @active.setter
# def active(self, value):
# self._active[:] = value
@property
def measured_period(self):
return self._api.getMeasuredPeriod()
# @property
# def measured_period(self):
# return self._api.getMeasuredPeriod()
@property
def measured_subperiod(self):
return self._api.getMeasuredSubPeriod()
# @property
# def measured_subperiod(self):
# return self._api.getMeasuredSubPeriod()
@property
def add_gappixels(self):
"""Enable or disable the (virual) pixels between ASICs
# @property
# def add_gappixels(self):
# """Enable or disable the (virual) pixels between ASICs
Examples
----------
# Examples
# ----------
::
# ::
d.add_gappixels = True
# d.add_gappixels = True
d.add_gappixels
>> True
# d.add_gappixels
# >> True
"""
return self._api.getGapPixels()
# """
# return self._api.getGapPixels()
@add_gappixels.setter
def add_gappixels(self, value):
self._api.setGapPixels(value)
# @add_gappixels.setter
# def add_gappixels(self, value):
# self._api.setGapPixels(value)
@property
def dacs(self):
@ -280,114 +284,68 @@ class Eiger(Detector):
"""
return self._dacs
@property
def tx_delay(self):
"""
Transmission delay of the modules to allow running the detector
in a network not supporting the full speed of the detector.
# @property
# def tx_delay(self):
# """
# Transmission delay of the modules to allow running the detector
# in a network not supporting the full speed of the detector.
::
# ::
d.tx_delay
>>
Transmission delay [ns]
left right frame
0:beb048 0 15000 0
1:beb049 100 190000 100
# d.tx_delay
# >>
# Transmission delay [ns]
# left right frame
# 0:beb048 0 15000 0
# 1:beb049 100 190000 100
d.tx_delay.left = [2000,5000]
"""
return self._delay
# d.tx_delay.left = [2000,5000]
# """
# return self._delay
def default_settings(self):
"""
reset the detector to some type of standard settings
mostly used when testing
"""
self.n_frames = 1
self.exposure_time = 1
self.period = 0
self.n_cycles = 1
self.n_measurements = 1
self.dynamic_range = 16
@property
def eiger_matrix_reset(self):
"""
Matrix reset bit for Eiger.
:py:obj:`True` : Normal operation, the matrix is reset before each acq.
:py:obj:`False` : Matrix reset disabled. Used to not reset before
reading out analog test pulses.
"""
return self._api.getCounterBit()
@eiger_matrix_reset.setter
def eiger_matrix_reset(self, value):
self._api.setCounterBit(value)
@property
def flowcontrol_10g(self):
"""
:py:obj:`True` - Flow control enabled :py:obj:`False` flow control disabled.
Sets for all moduels, if for some reason access to a single module is needed
this can be done trough the C++ API.
"""
fc = self._api.getNetworkParameter('flow_control_10g')
return element_if_equal([bool(int(e)) for e in fc])
@flowcontrol_10g.setter
def flowcontrol_10g(self, value):
if value is True:
v = '1'
else:
v = '0'
self._api.setNetworkParameter('flow_control_10g', v, -1)
def pulse_all_pixels(self, n):
"""
Pulse each pixel of the chip **n** times using the analog test pulses.
The pulse height is set using d.dacs.vcall with 4000 being 0 and 0 being
the highest pulse.
# def pulse_all_pixels(self, n):
# """
# Pulse each pixel of the chip **n** times using the analog test pulses.
# The pulse height is set using d.dacs.vcall with 4000 being 0 and 0 being
# the highest pulse.
::
# ::
#Pulse all pixels ten times
d.pulse_all_pixels(10)
# #Pulse all pixels ten times
# d.pulse_all_pixels(10)
#Avoid resetting before acq
d.eiger_matrix_reset = False
# #Avoid resetting before acq
# d.eiger_matrix_reset = False
d.acq() #take frame
# d.acq() #take frame
#Restore normal behaviour
d.eiger_matrix_reset = True
# #Restore normal behaviour
# d.eiger_matrix_reset = True
"""
self._api.pulseAllPixels(n)
# """
# self._api.pulseAllPixels(n)
def pulse_diagonal(self, n):
"""
Pulse pixels in super colums in a diagonal fashion. Used for calibration
of vcall. Saves time compared to pulsing all pixels.
"""
self._api.pulseDiagonal(n)
# def pulse_diagonal(self, n):
# """
# Pulse pixels in super colums in a diagonal fashion. Used for calibration
# of vcall. Saves time compared to pulsing all pixels.
# """
# self._api.pulseDiagonal(n)
def pulse_chip(self, n):
"""
Advance the counter by toggling enable. Gives 2*n+2 int the counter
# def pulse_chip(self, n):
# """
# Advance the counter by toggling enable. Gives 2*n+2 int the counter
"""
n = int(n)
if n >= -1:
self._api.pulseChip(n)
else:
raise ValueError('n must be equal or larger than -1')
# """
# n = int(n)
# if n >= -1:
# self._api.pulseChip(n)
# else:
# raise ValueError('n must be equal or larger than -1')
@property
def vcmp(self):
@ -420,177 +378,99 @@ class Eiger(Detector):
else:
raise ValueError('vcmp only compatible with setting all')
@property
def rx_udpport(self):
"""
UDP port for the receiver. Each module has two ports referred to
as rx_udpport and rx_udpport2 in the command line interface
here they are grouped for each detector
# @property
# def rx_udpport(self):
# """
# UDP port for the receiver. Each module has two ports referred to
# as rx_udpport and rx_udpport2 in the command line interface
# here they are grouped for each detector
::
# ::
[0:rx_udpport, 0:rx_udpport2, 1:rx_udpport ...]
# [0:rx_udpport, 0:rx_udpport2, 1:rx_udpport ...]
Examples
-----------
# Examples
# -----------
::
# ::
d.rx_udpport
>> [50010, 50011, 50004, 50005]
# d.rx_udpport
# >> [50010, 50011, 50004, 50005]
d.rx_udpport = [50010, 50011, 50012, 50013]
# d.rx_udpport = [50010, 50011, 50012, 50013]
"""
p0 = self._api.getReceiverUDPPort()
p1 = self._api.getReceiverUDPPort2()
return [int(val) for pair in zip(p0, p1) for val in pair]
# """
# p0 = self._api.getReceiverUDPPort()
# p1 = self._api.getReceiverUDPPort2()
# return [int(val) for pair in zip(p0, p1) for val in pair]
@rx_udpport.setter
def rx_udpport(self, ports):
"""Requires iterating over elements two and two for setting ports"""
a = iter(ports)
for i, p in enumerate(zip(a, a)):
self._api.setReceiverUDPPort(p[0], i)
self._api.setReceiverUDPPort2(p[1], i)
# @rx_udpport.setter
# def rx_udpport(self, ports):
# """Requires iterating over elements two and two for setting ports"""
# a = iter(ports)
# for i, p in enumerate(zip(a, a)):
# self._api.setReceiverUDPPort(p[0], i)
# self._api.setReceiverUDPPort2(p[1], i)
@property
def rx_zmqport(self):
"""
Return the receiver zmq ports. Note that Eiger has two ports per receiver!
This functions therefore differ from the base class.
::
detector.rx_zmqport
e.rx_zmqport
>> [30001, 30002, 30003, 30004]
"""
_s = self._api.getReceiverStreamingPort()
if _s == '':
return []
else:
return [int(_p) + i for _p in _s for i in range(2)]
@rx_zmqport.setter
def rx_zmqport(self, port):
if isinstance(port, Iterable):
for i, p in enumerate(port):
self._api.setReceiverStreamingPort(p, i)
else:
self._api.setReceiverStreamingPort(port, -1)
ports = self.getRxZmqPort()
return [p + i for p in ports for i in range(2)]
@property
def sub_exposure_time(self):
"""
Sub frame exposure time in *seconds* for Eiger in 32bit autosumming mode
# @rx_zmqport.setter
# def rx_zmqport(self, port):
# if isinstance(port, Iterable):
# for i, p in enumerate(port):
# self._api.setReceiverStreamingPort(p, i)
# else:
# self._api.setReceiverStreamingPort(port, -1)
::
# @property
# def temp(self):
# """
# An instance of DetectorAdcs used to read the temperature
# of different components
d.sub_exposure_time
>> 0.0023
# Examples
# -----------
d.sub_exposure_time = 0.002
# ::
"""
return self._api.getSubExposureTime() / 1e9
# detector.temp
# >>
# temp_fpga : 36.90°C, 45.60°C
# temp_fpgaext : 31.50°C, 32.50°C
# temp_10ge : 0.00°C, 0.00°C
# temp_dcdc : 36.00°C, 36.00°C
# temp_sodl : 33.00°C, 34.50°C
# temp_sodr : 33.50°C, 34.00°C
# temp_fpgafl : 33.81°C, 30.93°C
# temp_fpgafr : 27.88°C, 29.15°C
@sub_exposure_time.setter
def sub_exposure_time(self, t):
#TODO! checking here or in the detector?
ns_time = int(t * 1e9)
if ns_time > 0:
self._api.setSubExposureTime(ns_time)
else:
raise DetectorValueError('Sub exposure time must be larger than 0')
@property
def sub_deadtime(self):
"""
Deadtime between subexposures. Used to mimize noise by delaying the start of the next
subexposure.
"""
return self._api.getSubExposureDeadTime() / 1e9
@sub_deadtime.setter
def sub_deadtime(self, t):
ns_time = int(t * 1e9)
if ns_time >= 0:
self._api.setSubExposureDeadTime(ns_time)
else:
raise ValueError('Sub deadtime time must be larger or equal to 0')
@property
def temp(self):
"""
An instance of DetectorAdcs used to read the temperature
of different components
Examples
-----------
::
detector.temp
>>
temp_fpga : 36.90°C, 45.60°C
temp_fpgaext : 31.50°C, 32.50°C
temp_10ge : 0.00°C, 0.00°C
temp_dcdc : 36.00°C, 36.00°C
temp_sodl : 33.00°C, 34.50°C
temp_sodr : 33.50°C, 34.00°C
temp_fpgafl : 33.81°C, 30.93°C
temp_fpgafr : 27.88°C, 29.15°C
a = detector.temp.fpga[:]
a
>> [36.568, 45.542]
# a = detector.temp.fpga[:]
# a
# >> [36.568, 45.542]
"""
return self._temp
@property
def tengiga(self):
"""Enable 10Gbit/s data output
Examples
----------
::
d.tengiga
>> False
d.tengiga = True
"""
return self._api.getTenGigabitEthernet()
@tengiga.setter
def tengiga(self, value):
self._api.setTenGigabitEthernet(value)
def set_delays(self, delta):
self.tx_delay.left = [delta*(i*2) for i in range(self.n_modules)]
self.tx_delay.right = [delta*(i*2+1) for i in range(self.n_modules)]
# """
# return self._temp
# def set_delays(self, delta):
# self.tx_delay.left = [delta*(i*2) for i in range(self.n_modules)]
# self.tx_delay.right = [delta*(i*2+1) for i in range(self.n_modules)]
def setup500k(self, hostnames):
"""
Setup the Eiger detector to run on the local machine
"""
self.hostname = hostnames
self.file_write = False
self.image_size = (512, 1024)
self.rx_tcpport = [1954, 1955]
self.rx_udpport = [50010, 50011, 50004, 50005]
self.rx_hostname = socket.gethostname().split('.')[0]
self.rx_datastream = False
self.file_write = False
self.online = True
self.receiver_online = True

View File

@ -0,0 +1,54 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains the specialization for the Jungfrau detector
"""
from .detector import Detector, freeze
# from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs
import _sls_detector
dacIndex = _sls_detector.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty
# @freeze
class JungfrauDacs(DetectorDacs):
"""
Jungfrau specific DACs
"""
_dacs = [('vb_comp', dacIndex.VB_COMP, 0, 4000, 1220),
('vdd_prot', dacIndex.VDD_PROT, 0, 4000, 3000),
('vin_com', dacIndex.VIN_COM, 0, 4000, 1053),
('vref_prech', dacIndex.VREF_PRECH, 0, 4000, 1450),
('vb_pixbuff', dacIndex.VB_PIXBUF, 0, 4000, 750),
('vb_ds', dacIndex.VB_DS, 0, 4000, 1000),
('vref_ds', dacIndex.VREF_DS, 0, 4000, 480),
('vref_comp', dacIndex.VREF_COMP, 0, 4000, 420),
]
_dacnames = [_d[0] for _d in _dacs]
@freeze
class Jungfrau(Detector):
"""
Subclassing Detector to set up correct dacs and detector specific
functions.
"""
_detector_dynamic_range = [4, 8, 16, 32]
_settings = ['standard', 'highgain', 'lowgain', 'veryhighgain', 'verylowgain']
"""available settings for Eiger, note almost always standard"""
def __init__(self, id=0):
super().__init__(id)
self._frozen = False
self._dacs = JungfrauDacs(self)
@property
def dacs(self):
return self._dacs

View File

@ -0,0 +1,80 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains the specialization for the Jungfrau detector
"""
from .detector import Detector, freeze
# from .adcs import Adc, DetectorAdcs
from .dacs import DetectorDacs
import _sls_detector
dacIndex = _sls_detector.slsDetectorDefs.dacIndex
from .detector_property import DetectorProperty
# vcassh 1200,
# vth2 2800,
# vshaper 1280,
# vshaperneg 2800,
# vipre_out 1220,
# vth3 2800,
# vth1 2800,
# vicin 1708,
# vcas 1800,
# vpreamp 1100,
# vpl 1100,
# vipre 2624,
# viinsh 1708,
# vph 1712,
# vtrim 2800,
# vdcsh 800
# @freeze
class Mythen3Dacs(DetectorDacs):
"""
Jungfrau specific DACs
"""
_dacs = [('vcassh', dacIndex.CASSH, 0, 4000, 1220),
('vth2', dacIndex.VTH2, 0, 4000, 2800),
('vshaper', dacIndex.SHAPER1, 0, 4000, 1280),
('vshaperneg', dacIndex.SHAPER2, 0, 4000, 2800),
('vipre_out', dacIndex.VIPRE_OUT, 0, 4000, 1220),
('vth3', dacIndex.VTH3, 0, 4000, 2800),
('vth1', dacIndex.THRESHOLD, 0, 4000, 2800),
('vicin', dacIndex.VICIN, 0, 4000, 1708),
('vcas', dacIndex.CAS, 0, 4000, 1800),
('vpreamp', dacIndex.PREAMP, 0, 4000, 1100),
('vpl', dacIndex.VPL, 0, 4000, 1100),
('vipre', dacIndex.VIPRE, 0, 4000, 2624),
('viinsh', dacIndex.VIINSH, 0, 4000, 1708),
('vph', dacIndex.CALIBRATION_PULSE, 0, 4000, 1712),
('vtrim', dacIndex.TRIMBIT_SIZE, 0, 4000, 2800),
('vdcsh', dacIndex.VDCSH, 0, 4000, 800),
]
_dacnames = [_d[0] for _d in _dacs]
@freeze
class Mythen3(Detector):
"""
Subclassing Detector to set up correct dacs and detector specific
functions.
"""
_detector_dynamic_range = [4, 8, 16, 32]
_settings = ['standard', 'highgain', 'lowgain', 'veryhighgain', 'verylowgain']
"""available settings for Eiger, note almost always standard"""
def __init__(self, id=0):
super().__init__(id)
self._frozen = False
self._dacs = Mythen3Dacs(self)
@property
def dacs(self):
return self._dacs

View File

@ -3,14 +3,17 @@ class Register:
self._detector = detector
def __getitem__(self, key):
return self._detector._api.readRegister(key)
return self._detector.readRegister(key)
def __setitem__(self, key, value):
self._detector._api.writeRegister(key, value)
self._detector.writeRegister(key, value)
class Adc_register:
def __init__(self, detector):
self._detector = detector
def __setitem__(self, key, value):
self._detector._api.writeAdcRegister(key, value)
self._detector.writeAdcRegister(key, value)
def __getitem__(self, key):
raise ValueError('Adc registers cannot be read back')

View File

@ -4,9 +4,27 @@ but not directly used in controlling the detector
"""
from collections import namedtuple
import _sls_detector #C++ lib
import functools
Geometry = namedtuple('Geometry', ['x', 'y'])
def get_set_bits(mask):
"""
Return a list of the set bits in a python integer
"""
return [i for i in range(mask.bit_length()) if (mask>>i)&1]
def list_to_bitmask(values):
"""
Convert a list of integers to a bitmask with set bits
where the list indicates
"""
mask = int(0)
values = list(set(values)) #Remove duplicates
for v in values:
mask += 1 << v
return mask
def to_geo(value):
if isinstance(value, _sls_detector.xy):
return Geometry(x = value.x, y = value.y)
@ -28,6 +46,14 @@ def element_if_equal(mylist):
else:
return mylist
def element(func):
"""
Wrapper to return either list or element
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
return element_if_equal(func(self, *args, **kwargs))
return wrapper
def eiger_register_to_time(register):
"""

View File

@ -1,3 +1,6 @@
/* WARINING This file is auto generated any edits might be overwritten without
* warning */
#include <pybind11/chrono.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
@ -9,55 +12,60 @@
#include "sls_detector_defs.h"
#include "typecaster.h"
namespace py = pybind11;
void init_experimental(py::module &m) {
void init_det(py::module &m) {
using sls::Detector;
using sls::Positions;
using defs = slsDetectorDefs;
py::class_<Detector> CppDetectorApi(m, "CppDetectorApi");
CppDetectorApi
.def(py::init<int>())
// Configuration
.def("freeSharedMemory", (void (Detector::*)()) &Detector::freeSharedMemory)
.def("loadConfig", &Detector::loadConfig)
.def("loadParameters", &Detector::loadParameters)
.def("setHostname", &Detector::setHostname)
.def("freeSharedMemory", &Detector::freeSharedMemory)
.def("loadConfig", &Detector::loadConfig, py::arg())
.def("loadParameters", &Detector::loadParameters, py::arg())
.def("getHostname", &Detector::getHostname, py::arg() = Positions{})
.def("setHostname", &Detector::setHostname, py::arg())
.def("setVirtualDetectorServers", &Detector::setVirtualDetectorServers,
py::arg(), py::arg())
.def("getShmId", &Detector::getShmId)
.def("getPackageVersion", &Detector::getPackageVersion)
.def("getClientVersion", &Detector::getClientVersion)
.def("getFirmwareVersion", &Detector::getFirmwareVersion,
py::arg() = Positions{})
.def("getDetectorServerVersion", &Detector::getDetectorServerVersion,
py::arg() = Positions{})
.def("getSerialNumber", &Detector::getSerialNumber,
py::arg() = Positions{})
.def("getClientVersion", &Detector::getClientVersion)
.def("getReceiverVersion", &Detector::getReceiverVersion,
py::arg() = Positions{})
.def("getDetectorType", &Detector::getDetectorType,
py::arg() = Positions{})
.def("size", &Detector::size)
.def("empty", &Detector::empty)
.def("getModuleGeometry", &Detector::getModuleGeometry)
.def("getModuleSize", &Detector::getModuleSize, py::arg() = Positions{})
.def("getDetectorSize", &Detector::getDetectorSize)
.def("setDetectorSize", &Detector::setDetectorSize)
.def("setDetectorSize", &Detector::setDetectorSize, py::arg())
.def("getSettings", &Detector::getSettings, py::arg() = Positions{})
.def("setSettings", &Detector::setSettings, py::arg(),
py::arg() = Positions{})
// TODO! Python funcs for callbacks?
// Acquisition Parameters
.def("getNumberOfFrames", &Detector::getNumberOfFrames)
.def("setNumberOfFrames", &Detector::setNumberOfFrames)
.def("getNumberOfTriggers", &Detector::getNumberOfTriggers)
.def("setNumberOfTriggers", &Detector::setNumberOfTriggers)
.def("registerAcquisitionFinishedCallback",
&Detector::registerAcquisitionFinishedCallback, py::arg(),
py::arg())
.def("registerDataCallback", &Detector::registerDataCallback, py::arg(),
py::arg())
.def("getNumberOfFrames", &Detector::getNumberOfFrames,
py::arg() = Positions{})
.def("setNumberOfFrames", &Detector::setNumberOfFrames, py::arg())
.def("getNumberOfTriggers", &Detector::getNumberOfTriggers,
py::arg() = Positions{})
.def("setNumberOfTriggers", &Detector::setNumberOfTriggers, py::arg())
.def("getExptime", &Detector::getExptime, py::arg() = Positions{})
.def("setExptime", &Detector::setExptime, py::arg(),
py::arg() = Positions{})
.def("getExptime", &Detector::getExptime, py::arg() = Positions{})
.def("getPeriod", &Detector::getPeriod, py::arg() = Positions{})
.def("setPeriod", &Detector::setPeriod, py::arg(),
py::arg() = Positions{})
.def("getPeriod", &Detector::getPeriod, py::arg() = Positions{})
.def("getDelayAfterTrigger", &Detector::getDelayAfterTrigger,
py::arg() = Positions{})
.def("setDelayAfterTrigger", &Detector::setDelayAfterTrigger, py::arg(),
@ -68,196 +76,124 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("getDelayAfterTriggerLeft", &Detector::getDelayAfterTriggerLeft,
py::arg() = Positions{})
.def("getPeriodLeft", &Detector::getPeriodLeft, py::arg() = Positions{})
.def("getSpeed", &Detector::getSpeed, py::arg() = Positions{})
.def("setSpeed", &Detector::setSpeed, py::arg(),
py::arg() = Positions{})
.def("getADCPhase", &Detector::getADCPhase, py::arg() = Positions{})
.def("setADCPhase", &Detector::setADCPhase, py::arg(),
py::arg() = Positions{})
.def("getMaxADCPhaseShift", &Detector::getMaxADCPhaseShift,
py::arg() = Positions{})
.def("getADCPhaseInDegrees", &Detector::getADCPhaseInDegrees,
py::arg() = Positions{})
.def("setADCPhaseInDegrees", &Detector::setADCPhaseInDegrees, py::arg(),
py::arg() = Positions{})
.def("getClockFrequency", &Detector::getClockFrequency, py::arg(),
py::arg() = Positions{})
.def("setClockFrequency", &Detector::setClockFrequency, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getClockPhase", &Detector::getClockPhase, py::arg(),
py::arg() = Positions{})
.def("setClockPhase", &Detector::setClockPhase, py::arg(), py::arg(),
py::arg() = Positions{})
.def("getMaxClockPhaseShift", &Detector::getMaxClockPhaseShift,
py::arg(), py::arg() = Positions{})
.def("getClockPhaseinDegrees", &Detector::getClockPhaseinDegrees,
py::arg(), py::arg() = Positions{})
.def("setClockPhaseinDegrees", &Detector::setClockPhaseinDegrees,
py::arg(), py::arg(), py::arg() = Positions{})
.def("getClockDivider", &Detector::getClockDivider, py::arg(),
py::arg() = Positions{})
.def("setClockDivider", &Detector::setClockDivider, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getHighVoltage", &Detector::getHighVoltage,
py::arg() = Positions{})
.def("setHighVoltage", &Detector::setHighVoltage, py::arg(),
py::arg() = Positions{})
.def("getTemperature", &Detector::getTemperature, py::arg(),
py::arg() = Positions{})
.def("getDAC", &Detector::getDAC, py::arg(), py::arg() = false,
.def("getDAC", &Detector::getDAC, py::arg(), py::arg(),
py::arg() = Positions{})
.def("setDAC", &Detector::setDAC, py::arg(), py::arg(), py::arg(),
py::arg() = Positions{})
.def("getOnChipDAC", &Detector::getOnChipDAC, py::arg(), py::arg(),
py::arg() = Positions{})
.def("setOnChipDAC", &Detector::setOnChipDAC, py::arg(), py::arg(),
py::arg(), py::arg() = Positions{})
.def("getTimingMode", &Detector::getTimingMode, py::arg() = Positions{})
.def("setTimingMode", &Detector::setTimingMode, py::arg(),
py::arg() = Positions{})
// ACQUISITION
.def("acquire", &Detector::acquire)
.def("startDetector", &Detector::startDetector)
.def("stopDetector", &Detector::stopDetector)
.def("clearAcquiringFlag", &Detector::clearAcquiringFlag)
.def("startReceiver", &Detector::startReceiver)
.def("stopReceiver", &Detector::stopReceiver)
.def("clearAcquiringFlag", &Detector::clearAcquiringFlag)
.def("startDetector", &Detector::startDetector)
.def("stopDetector", &Detector::stopDetector)
.def("getDetectorStatus", &Detector::getDetectorStatus,
py::arg() = Positions{})
.def("getReceiverStatus", &Detector::getReceiverStatus,
py::arg() = Positions{})
.def("getFramesCaught", &Detector::getFramesCaught,
py::arg() = Positions{})
.def("getNumMissingPackets", &Detector::getNumMissingPackets,
py::arg() = Positions{})
.def("getStartingFrameNumber", &Detector::getStartingFrameNumber,
py::arg() = Positions{})
.def("setStartingFrameNumber", &Detector::setStartingFrameNumber,
py::arg(), py::arg() = Positions{})
.def("sendSoftwareTrigger", &Detector::sendSoftwareTrigger,
py::arg() = Positions{})
// Network Configuration (Detector<->Receiver)
.def("getNumberofUDPInterfaces", &Detector::getNumberofUDPInterfaces,
py::arg() = Positions{})
.def("setNumberofUDPInterfaces", &Detector::setNumberofUDPInterfaces,
py::arg(), py::arg() = Positions{})
.def("getSelectedUDPInterface", &Detector::getSelectedUDPInterface,
py::arg() = Positions{})
.def("selectUDPInterface", &Detector::selectUDPInterface, py::arg(),
py::arg() = Positions{})
// Using lambda to allow for conversion from IpAddr
.def("getSourceUDPIP",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getSourceUDPIP(pos))
res.push_back(s.str());
return res;
},
.def("getSourceUDPIP", &Detector::getSourceUDPIP,
py::arg() = Positions{})
.def("setSourceUDPIP",
[](Detector &d, std::string ip, Positions pos) {
d.setSourceUDPIP(sls::IpAddr(ip), pos);
},
py::arg(), py::arg() = Positions{})
.def("getSourceUDPIP2",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getSourceUDPIP2(pos))
res.push_back(s.str());
return res;
},
.def("setSourceUDPIP", &Detector::setSourceUDPIP, py::arg(),
py::arg() = Positions{})
.def("setSourceUDPIP2",
[](Detector &d, std::string ip, Positions pos) {
d.setSourceUDPIP2(sls::IpAddr(ip), pos);
},
py::arg(), py::arg() = Positions{})
.def("getSourceUDPMAC",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getSourceUDPMAC(pos))
res.push_back(s.str());
return res;
},
.def("getSourceUDPIP2", &Detector::getSourceUDPIP2,
py::arg() = Positions{})
.def("setSourceUDPMAC",
[](Detector &d, std::string mac, Positions pos) {
d.setSourceUDPMAC(sls::MacAddr(mac), pos);
},
py::arg(), py::arg() = Positions{})
.def("getSourceUDPMAC2",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getSourceUDPMAC2(pos))
res.push_back(s.str());
return res;
},
.def("setSourceUDPIP2", &Detector::setSourceUDPIP2, py::arg(),
py::arg() = Positions{})
.def("setSourceUDPMAC2",
[](Detector &d, std::string mac, Positions pos) {
d.setSourceUDPMAC2(sls::MacAddr(mac), pos);
},
py::arg(), py::arg() = Positions{})
.def("getDestinationUDPIP",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getDestinationUDPIP(pos))
res.push_back(s.str());
return res;
},
.def("getSourceUDPMAC", &Detector::getSourceUDPMAC,
py::arg() = Positions{})
.def("setDestinationUDPIP",
[](Detector &d, std::string ip, Positions pos) {
d.setDestinationUDPIP(sls::IpAddr(ip), pos);
},
py::arg(), py::arg() = Positions{})
.def("getDestinationUDPIP2",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getDestinationUDPIP2(pos))
res.push_back(s.str());
return res;
},
.def("setSourceUDPMAC", &Detector::setSourceUDPMAC, py::arg(),
py::arg() = Positions{})
.def("setDestinationUDPIP2",
[](Detector &d, std::string ip, Positions pos) {
d.setDestinationUDPIP2(sls::IpAddr(ip), pos);
},
py::arg(), py::arg() = Positions{})
.def("getDestinationUDPMAC",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getDestinationUDPMAC(pos))
res.push_back(s.str());
return res;
},
.def("getSourceUDPMAC2", &Detector::getSourceUDPMAC2,
py::arg() = Positions{})
.def("setDestinationUDPMAC",
[](Detector &d, std::string mac, Positions pos) {
d.setDestinationUDPMAC(sls::MacAddr(mac), pos);
},
py::arg(), py::arg() = Positions{})
.def("getDestinationUDPMAC2",
[](const Detector &d, Positions pos) {
std::vector<std::string> res;
for (const auto &s : d.getDestinationUDPMAC2(pos))
res.push_back(s.str());
return res;
},
.def("setSourceUDPMAC2", &Detector::setSourceUDPMAC2, py::arg(),
py::arg() = Positions{})
.def("setDestinationUDPMAC2",
[](Detector &d, std::string mac, Positions pos) {
d.setDestinationUDPMAC2(sls::MacAddr(mac), pos);
},
.def("getDestinationUDPIP", &Detector::getDestinationUDPIP,
py::arg() = Positions{})
.def("setDestinationUDPIP", &Detector::setDestinationUDPIP, py::arg(),
py::arg() = Positions{})
.def("getDestinationUDPIP2", &Detector::getDestinationUDPIP2,
py::arg() = Positions{})
.def("setDestinationUDPIP2", &Detector::setDestinationUDPIP2, py::arg(),
py::arg() = Positions{})
.def("getDestinationUDPMAC", &Detector::getDestinationUDPMAC,
py::arg() = Positions{})
.def("setDestinationUDPMAC", &Detector::setDestinationUDPMAC, py::arg(),
py::arg() = Positions{})
.def("getDestinationUDPMAC2", &Detector::getDestinationUDPMAC2,
py::arg() = Positions{})
.def("setDestinationUDPMAC2", &Detector::setDestinationUDPMAC2,
py::arg(), py::arg() = Positions{})
.def("getDestinationUDPPort", &Detector::getDestinationUDPPort,
py::arg() = Positions{})
.def("setDestinationUDPPort", &Detector::setDestinationUDPPort,
py::arg(), py::arg() = Positions{})
py::arg(), py::arg())
.def("getDestinationUDPPort2", &Detector::getDestinationUDPPort2,
py::arg() = Positions{})
.def("setDestinationUDPPort2", &Detector::setDestinationUDPPort2,
py::arg(), py::arg() = Positions{})
py::arg(), py::arg())
.def("printRxConfiguration", &Detector::printRxConfiguration,
py::arg() = Positions{})
.def("getTenGiga", &Detector::getTenGiga, py::arg() = Positions{})
.def("setTenGiga", &Detector::setTenGiga, py::arg(),
py::arg() = Positions{})
@ -269,7 +205,6 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("setTransmissionDelayFrame", &Detector::setTransmissionDelayFrame,
py::arg(), py::arg() = Positions{})
.def("getTransmissionDelayLeft", &Detector::getTransmissionDelayLeft,
py::arg() = Positions{})
.def("setTransmissionDelayLeft", &Detector::setTransmissionDelayLeft,
@ -278,21 +213,13 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("setTransmissionDelayRight", &Detector::setTransmissionDelayRight,
py::arg(), py::arg() = Positions{})
/**************************************************
* *
* RECEIVER CONFIG *
* *
* ************************************************/
.def("getUseReceiverFlag", &Detector::getUseReceiverFlag,
py::arg() = Positions{})
.def("getRxHostname", &Detector::getRxHostname, py::arg() = Positions{})
.def("setRxHostname", &Detector::setRxHostname, py::arg(),
py::arg() = Positions{})
.def("getRxPort", &Detector::getRxPort, py::arg() = Positions{})
.def("setRxPort", &Detector::setRxPort, py::arg(),
py::arg() = Positions{})
.def("setRxPort", &Detector::setRxPort, py::arg(), py::arg())
.def("getRxFifoDepth", &Detector::getRxFifoDepth,
py::arg() = Positions{})
.def("setRxFifoDepth", &Detector::setRxFifoDepth, py::arg(),
@ -320,12 +247,6 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("getRxLastClientIP", &Detector::getRxLastClientIP,
py::arg() = Positions{})
/**************************************************
* *
* FILE *
* *
* ************************************************/
.def("getFileFormat", &Detector::getFileFormat, py::arg() = Positions{})
.def("setFileFormat", &Detector::setFileFormat, py::arg(),
py::arg() = Positions{})
@ -336,36 +257,25 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("setFileNamePrefix", &Detector::setFileNamePrefix, py::arg(),
py::arg() = Positions{})
.def("getFilePath", &Detector::getFilePath)
.def("setFilePath", &Detector::setFilePath, py::arg(),
py::arg() = Positions{})
.def("getAcquisitionIndex", &Detector::getAcquisitionIndex,
py::arg() = Positions{})
.def("setAcquisitionIndex", &Detector::setAcquisitionIndex, py::arg(),
py::arg() = Positions{})
.def("setFileWrite", &Detector::setFileWrite, py::arg(),
py::arg() = Positions{})
.def("getFileWrite", &Detector::getFileWrite, py::arg() = Positions{})
.def("setFileOverWrite", &Detector::setFileOverWrite, py::arg(),
py::arg() = Positions{})
.def("getFileOverWrite", &Detector::getFileOverWrite,
py::arg() = Positions{})
.def("setMasterFileWrite", &Detector::setMasterFileWrite, py::arg(),
.def("setFileWrite", &Detector::setFileWrite, py::arg(),
py::arg() = Positions{})
.def("getMasterFileWrite", &Detector::getMasterFileWrite,
py::arg() = Positions{})
.def("setFramesPerFile", &Detector::setFramesPerFile, py::arg(),
.def("setMasterFileWrite", &Detector::setMasterFileWrite, py::arg(),
py::arg() = Positions{})
.def("getFileOverWrite", &Detector::getFileOverWrite,
py::arg() = Positions{})
.def("setFileOverWrite", &Detector::setFileOverWrite, py::arg(),
py::arg() = Positions{})
.def("getFramesPerFile", &Detector::getFramesPerFile,
py::arg() = Positions{})
/**************************************************
* *
* ZMQ Streaming Parameters (Receiver<->Client)*
* *
* ************************************************/
.def("setFramesPerFile", &Detector::setFramesPerFile, py::arg(),
py::arg() = Positions{})
.def("getRxZmqDataStream", &Detector::getRxZmqDataStream,
py::arg() = Positions{})
.def("setRxZmqDataStream", &Detector::setRxZmqDataStream, py::arg(),
@ -378,29 +288,21 @@ void init_experimental(py::module &m) {
.def("setRxZmqTimer", &Detector::setRxZmqTimer, py::arg(),
py::arg() = Positions{})
.def("getRxZmqPort", &Detector::getRxZmqPort, py::arg() = Positions{})
.def("setRxZmqPort", &Detector::setRxZmqPort, py::arg(),
py::arg() = Positions{})
.def("setRxZmqPort", &Detector::setRxZmqPort, py::arg(), py::arg())
.def("getRxZmqIP", &Detector::getRxZmqIP, py::arg() = Positions{})
.def("setRxZmqIP", &Detector::setRxZmqIP, py::arg(),
py::arg() = Positions{})
.def("getClientZmqPort", &Detector::getClientZmqPort,
py::arg() = Positions{})
.def("setClientZmqPort", &Detector::setClientZmqPort, py::arg(),
py::arg() = -1)
py::arg())
.def("getClientZmqIp", &Detector::getClientZmqIp,
py::arg() = Positions{})
.def("setClientZmqIp", &Detector::setClientZmqIp, py::arg(),
py::arg() = Positions{})
/**************************************************
* *
* Eiger Specific *
* *
* ************************************************/
.def("getDynamicRange", &Detector::getDynamicRange,
py::arg() = Positions{})
.def("setDynamicRange", &Detector::setDynamicRange)
.def("setDynamicRange", &Detector::setDynamicRange, py::arg())
.def("getSubExptime", &Detector::getSubExptime, py::arg() = Positions{})
.def("setSubExptime", &Detector::setSubExptime, py::arg(),
py::arg() = Positions{})
@ -408,12 +310,10 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("setSubDeadTime", &Detector::setSubDeadTime, py::arg(),
py::arg() = Positions{})
.def("getThresholdEnergy", &Detector::getThresholdEnergy,
py::arg() = Positions{})
.def("setThresholdEnergy", &Detector::setThresholdEnergy, py::arg(),
py::arg() = defs::STANDARD, py::arg() = true,
py::arg() = Positions{})
py::arg(), py::arg(), py::arg() = Positions{})
.def("getSettingsPath", &Detector::getSettingsPath,
py::arg() = Positions{})
.def("setSettingsPath", &Detector::setSettingsPath, py::arg(),
@ -422,7 +322,7 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("getRxAddGapPixels", &Detector::getRxAddGapPixels,
py::arg() = Positions{})
.def("setRxAddGapPixels", &Detector::setRxAddGapPixels)
.def("setRxAddGapPixels", &Detector::setRxAddGapPixels, py::arg())
.def("getParallelMode", &Detector::getParallelMode,
py::arg() = Positions{})
.def("setParallelMode", &Detector::setParallelMode, py::arg(),
@ -448,10 +348,10 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("getRateCorrection", &Detector::getRateCorrection,
py::arg() = Positions{})
.def("setRateCorrection", &Detector::setRateCorrection, py::arg(),
py::arg() = Positions{})
.def("setDefaultRateCorrection", &Detector::setDefaultRateCorrection,
py::arg() = Positions{})
.def("setRateCorrection", &Detector::setRateCorrection, py::arg(),
py::arg() = Positions{})
.def("getPartialReadout", &Detector::getPartialReadout,
py::arg() = Positions{})
.def("setPartialReadout", &Detector::setPartialReadout, py::arg(),
@ -460,7 +360,6 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("setInterruptSubframe", &Detector::setInterruptSubframe, py::arg(),
py::arg() = Positions{})
.def("getMeasuredPeriod", &Detector::getMeasuredPeriod,
py::arg() = Positions{})
.def("getMeasuredSubFramePeriod", &Detector::getMeasuredSubFramePeriod,
@ -476,7 +375,6 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("setPartialReset", &Detector::setPartialReset, py::arg(),
py::arg() = Positions{})
.def("pulsePixel", &Detector::pulsePixel, py::arg(), py::arg(),
py::arg() = Positions{})
.def("pulsePixelNMove", &Detector::pulsePixelNMove, py::arg(),
@ -484,13 +382,7 @@ void init_experimental(py::module &m) {
.def("pulseChip", &Detector::pulseChip, py::arg(),
py::arg() = Positions{})
.def("getQuad", &Detector::getQuad, py::arg() = Positions{})
.def("setQuad", &Detector::setQuad)
/**************************************************
* *
* Jungfrau Specific *
* *
* ************************************************/
.def("setQuad", &Detector::setQuad, py::arg())
.def("getThresholdTemperature", &Detector::getThresholdTemperature,
py::arg() = Positions{})
.def("setThresholdTemperature", &Detector::setThresholdTemperature,
@ -503,7 +395,6 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("resetTemperatureEvent", &Detector::resetTemperatureEvent,
py::arg() = Positions{})
.def("getPowerChip", &Detector::getPowerChip, py::arg() = Positions{})
.def("setPowerChip", &Detector::setPowerChip, py::arg(),
py::arg() = Positions{})
@ -511,70 +402,49 @@ void init_experimental(py::module &m) {
py::arg() = Positions{})
.def("setAutoCompDisable", &Detector::setAutoCompDisable, py::arg(),
py::arg() = Positions{})
.def("getNumberOfAdditionalStorageCells",
&Detector::getNumberOfAdditionalStorageCells)
&Detector::getNumberOfAdditionalStorageCells,
py::arg() = Positions{})
.def("setNumberOfAdditionalStorageCells",
&Detector::setNumberOfAdditionalStorageCells)
&Detector::setNumberOfAdditionalStorageCells, py::arg())
.def("getStorageCellStart", &Detector::getStorageCellStart,
py::arg() = Positions{})
.def("setStoragecellStart", &Detector::setStoragecellStart, py::arg(),
py::arg() = Positions{})
.def("getStorageCellDelay", &Detector::getStorageCellDelay,
py::arg() = Positions{})
.def("setStorageCellDelay", &Detector::setStorageCellDelay, py::arg(),
py::arg() = Positions{})
// Bits and registers
.def("setBit", &Detector::setBit, py::arg(), py::arg(),
.def("getROI", &Detector::getROI, py::arg() = Positions{})
.def("setROI", &Detector::setROI, py::arg(), py::arg())
.def("clearROI", &Detector::clearROI, py::arg() = Positions{})
.def("getExptimeLeft", &Detector::getExptimeLeft,
py::arg() = Positions{})
.def("clearBit", &Detector::clearBit, py::arg(), py::arg(),
.def("getExternalSignalFlags", &Detector::getExternalSignalFlags,
py::arg() = Positions{})
.def("readRegister", &Detector::readRegister, py::arg(),
py::arg() = Positions{})
.def("writeRegister", &Detector::writeRegister, py::arg(), py::arg(),
py::arg() = Positions{})
.def("getStartingFrameNumber", &Detector::getStartingFrameNumber,
py::arg() = Positions{})
.def("setStartingFrameNumber", &Detector::setStartingFrameNumber,
.def("setExternalSignalFlags", &Detector::setExternalSignalFlags,
py::arg(), py::arg() = Positions{})
/**************************************************
* *
* Insignificant *
* *
* ************************************************/
.def("getControlPort", &Detector::getControlPort,
.def("getImageTestMode", &Detector::getImageTestMode,
py::arg() = Positions{})
.def("setControlPort", &Detector::setControlPort, py::arg(),
.def("setImageTestMode", &Detector::setImageTestMode, py::arg(),
py::arg() = Positions{})
.def("getStopPort", &Detector::getStopPort, py::arg() = Positions{})
.def("setStopPort", &Detector::setStopPort, py::arg(),
.def("getInjectChannel", &Detector::getInjectChannel,
py::arg() = Positions{})
.def("getDetectorLock", &Detector::getDetectorLock,
.def("setInjectChannel", &Detector::setInjectChannel, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getVetoPhoton", &Detector::getVetoPhoton, py::arg(),
py::arg() = Positions{})
.def("setDetectorLock", &Detector::setDetectorLock, py::arg(),
.def("setVetoPhoton", &Detector::setVetoPhoton, py::arg(), py::arg(),
py::arg(), py::arg(), py::arg() = Positions{})
.def("setVetoReference", &Detector::setVetoReference, py::arg(),
py::arg(), py::arg() = Positions{})
.def("setBurstMode", &Detector::setBurstMode, py::arg(),
py::arg() = Positions{})
.def("getLastClientIP", &Detector::getLastClientIP,
.def("getBurstMode", &Detector::getBurstMode, py::arg() = Positions{})
.def("getCounterMask", &Detector::getCounterMask,
py::arg() = Positions{})
.def("executeCommand", &Detector::executeCommand, py::arg(),
.def("setCounterMask", &Detector::setCounterMask, py::arg(),
py::arg() = Positions{})
.def("getNumberOfFramesFromStart",
&Detector::getNumberOfFramesFromStart, py::arg() = Positions{})
.def("getActualTime", &Detector::getActualTime, py::arg() = Positions{})
.def("getMeasurementTime", &Detector::getMeasurementTime,
py::arg() = Positions{})
.def("getUserDetails", &Detector::getUserDetails)
.def("getRxCurrentFrameIndex", &Detector::getRxCurrentFrameIndex,
py::arg() = Positions{})
/**************************************************
* *
* CTB Specific *
* *
* ************************************************/
.def("getNumberOfAnalogSamples", &Detector::getNumberOfAnalogSamples,
py::arg() = Positions{})
.def("setNumberOfAnalogSamples", &Detector::setNumberOfAnalogSamples,
@ -606,11 +476,161 @@ void init_experimental(py::module &m) {
.def("setRUNClock", &Detector::setRUNClock, py::arg(),
py::arg() = Positions{})
.def("getSYNCClock", &Detector::getSYNCClock, py::arg() = Positions{})
// Time
.def("setSubExptime", &Detector::setSubExptime, py::arg(),
.def("getADCPipeline", &Detector::getADCPipeline,
py::arg() = Positions{})
.def("getSubExptime", &Detector::getSubExptime,
.def("setADCPipeline", &Detector::setADCPipeline, py::arg(),
py::arg() = Positions{})
.def("getDBITPipeline", &Detector::getDBITPipeline,
py::arg() = Positions{})
.def("setDBITPipeline", &Detector::setDBITPipeline, py::arg(),
py::arg() = Positions{})
.def("getVoltage", &Detector::getVoltage, py::arg(),
py::arg() = Positions{})
.def("setVoltage", &Detector::setVoltage, py::arg(), py::arg(),
py::arg() = Positions{})
.def("getMeasuredVoltage", &Detector::getMeasuredVoltage, py::arg(),
py::arg() = Positions{})
.def("getMeasuredCurrent", &Detector::getMeasuredCurrent, py::arg(),
py::arg() = Positions{})
.def("getSlowADC", &Detector::getSlowADC, py::arg(),
py::arg() = Positions{})
.def("getADCEnableMask", &Detector::getADCEnableMask,
py::arg() = Positions{})
.def("setADCEnableMask", &Detector::setADCEnableMask, py::arg(),
py::arg() = Positions{})
.def("getTenGigaADCEnableMask", &Detector::getTenGigaADCEnableMask,
py::arg() = Positions{})
.def("setTenGigaADCEnableMask", &Detector::setTenGigaADCEnableMask,
py::arg(), py::arg() = Positions{})
.def("getADCInvert", &Detector::getADCInvert, py::arg() = Positions{})
.def("setADCInvert", &Detector::setADCInvert, py::arg(),
py::arg() = Positions{})
.def("getExternalSamplingSource", &Detector::getExternalSamplingSource,
py::arg() = Positions{})
.def("setExternalSamplingSource", &Detector::setExternalSamplingSource,
py::arg(), py::arg() = Positions{})
.def("getExternalSampling", &Detector::getExternalSampling,
py::arg() = Positions{})
.def("setExternalSampling", &Detector::setExternalSampling, py::arg(),
py::arg() = Positions{})
.def("getRxDbitList", &Detector::getRxDbitList, py::arg() = Positions{})
.def("setRxDbitList", &Detector::setRxDbitList, py::arg(),
py::arg() = Positions{})
.def("getRxDbitOffset", &Detector::getRxDbitOffset,
py::arg() = Positions{})
.def("setRxDbitOffset", &Detector::setRxDbitOffset, py::arg(),
py::arg() = Positions{})
.def("setDigitalIODelay", &Detector::setDigitalIODelay, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getLEDEnable", &Detector::getLEDEnable, py::arg() = Positions{})
.def("setLEDEnable", &Detector::setLEDEnable, py::arg(),
py::arg() = Positions{})
.def("setPattern", &Detector::setPattern, py::arg(),
py::arg() = Positions{})
.def("savePattern", &Detector::savePattern, py::arg())
.def("getPatternIOControl", &Detector::getPatternIOControl,
py::arg() = Positions{})
.def("setPatternIOControl", &Detector::setPatternIOControl, py::arg(),
py::arg() = Positions{})
.def("getPatternClockControl", &Detector::getPatternClockControl,
py::arg() = Positions{})
.def("setPatternClockControl", &Detector::setPatternClockControl,
py::arg(), py::arg() = Positions{})
.def("getPatternWord", &Detector::getPatternWord, py::arg(),
py::arg() = Positions{})
.def("setPatternWord", &Detector::setPatternWord, py::arg(), py::arg(),
py::arg() = Positions{})
.def("getPatternLoopAddresses", &Detector::getPatternLoopAddresses,
py::arg(), py::arg() = Positions{})
.def("setPatternLoopAddresses", &Detector::setPatternLoopAddresses,
py::arg(), py::arg(), py::arg(), py::arg() = Positions{})
.def("getPatternLoopCycles", &Detector::getPatternLoopCycles, py::arg(),
py::arg() = Positions{})
.def("setPatternLoopCycles", &Detector::setPatternLoopCycles, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getPatternWaitAddr", &Detector::getPatternWaitAddr, py::arg(),
py::arg() = Positions{})
.def("setPatternWaitAddr", &Detector::setPatternWaitAddr, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getPatternWaitTime", &Detector::getPatternWaitTime, py::arg(),
py::arg() = Positions{})
.def("setPatternWaitTime", &Detector::setPatternWaitTime, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getPatternMask", &Detector::getPatternMask,
py::arg() = Positions{})
.def("setPatternMask", &Detector::setPatternMask, py::arg(),
py::arg() = Positions{})
.def("getPatternBitMask", &Detector::getPatternBitMask,
py::arg() = Positions{})
.def("setPatternBitMask", &Detector::setPatternBitMask, py::arg(),
py::arg() = Positions{})
.def("getAdditionalJsonHeader", &Detector::getAdditionalJsonHeader,
py::arg() = Positions{})
.def("setAdditionalJsonHeader", &Detector::setAdditionalJsonHeader,
py::arg(), py::arg() = Positions{})
.def("getAdditionalJsonParameter",
&Detector::getAdditionalJsonParameter, py::arg(),
py::arg() = Positions{})
.def("setAdditionalJsonParameter",
&Detector::setAdditionalJsonParameter, py::arg(), py::arg(),
py::arg() = Positions{})
.def("getDetectorMinMaxEnergyThreshold",
&Detector::getDetectorMinMaxEnergyThreshold, py::arg(),
py::arg() = Positions{})
.def("setDetectorMinMaxEnergyThreshold",
&Detector::setDetectorMinMaxEnergyThreshold, py::arg(), py::arg(),
py::arg() = Positions{})
.def("getFrameMode", &Detector::getFrameMode, py::arg() = Positions{})
.def("setFrameMode", &Detector::setFrameMode, py::arg(),
py::arg() = Positions{})
.def("getDetectorMode", &Detector::getDetectorMode,
py::arg() = Positions{})
.def("setDetectorMode", &Detector::setDetectorMode, py::arg(),
py::arg() = Positions{})
.def("programFPGA", &Detector::programFPGA, py::arg(),
py::arg() = Positions{})
.def("resetFPGA", &Detector::resetFPGA, py::arg() = Positions{})
.def("copyDetectorServer", &Detector::copyDetectorServer, py::arg(),
py::arg(), py::arg() = Positions{})
.def("rebootController", &Detector::rebootController,
py::arg() = Positions{})
.def("updateFirmwareAndServer", &Detector::updateFirmwareAndServer,
py::arg(), py::arg(), py::arg(), py::arg() = Positions{})
.def("readRegister", &Detector::readRegister, py::arg(),
py::arg() = Positions{})
.def("writeRegister", &Detector::writeRegister, py::arg(), py::arg(),
py::arg() = Positions{})
.def("setBit", &Detector::setBit, py::arg(), py::arg(),
py::arg() = Positions{})
.def("clearBit", &Detector::clearBit, py::arg(), py::arg(),
py::arg() = Positions{})
.def("executeFirmwareTest", &Detector::executeFirmwareTest,
py::arg() = Positions{})
.def("executeBusTest", &Detector::executeBusTest,
py::arg() = Positions{})
.def("writeAdcRegister", &Detector::writeAdcRegister, py::arg(),
py::arg(), py::arg() = Positions{})
.def("getControlPort", &Detector::getControlPort,
py::arg() = Positions{})
.def("setControlPort", &Detector::setControlPort, py::arg(),
py::arg() = Positions{})
.def("getStopPort", &Detector::getStopPort, py::arg() = Positions{})
.def("setStopPort", &Detector::setStopPort, py::arg(),
py::arg() = Positions{})
.def("getDetectorLock", &Detector::getDetectorLock,
py::arg() = Positions{})
.def("setDetectorLock", &Detector::setDetectorLock, py::arg(),
py::arg() = Positions{})
.def("getLastClientIP", &Detector::getLastClientIP,
py::arg() = Positions{})
.def("executeCommand", &Detector::executeCommand, py::arg(),
py::arg() = Positions{})
.def("getNumberOfFramesFromStart",
&Detector::getNumberOfFramesFromStart, py::arg() = Positions{})
.def("getActualTime", &Detector::getActualTime, py::arg() = Positions{})
.def("getMeasurementTime", &Detector::getMeasurementTime,
py::arg() = Positions{})
.def("getUserDetails", &Detector::getUserDetails)
.def("getRxCurrentFrameIndex", &Detector::getRxCurrentFrameIndex,
py::arg() = Positions{});
}

View File

@ -0,0 +1,21 @@
#include <pybind11/chrono.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "Detector.h"
#include "ToString.h"
#include "network_utils.h"
#include "sls_detector_defs.h"
#include "typecaster.h"
namespace py = pybind11;
void init_det(py::module &m) {
using sls::Detector;
using sls::Positions;
py::class_<Detector> CppDetectorApi(m, "CppDetectorApi");
CppDetectorApi
.def(py::init<int>())
[[FUNCTIONS]]
}

View File

@ -17,6 +17,8 @@ using ds = std::chrono::duration<double>;
namespace py = pybind11;
void init_enums(py::module &);
void init_experimental(py::module &);
void init_det(py::module &);
void init_network(py::module &);
PYBIND11_MODULE(_sls_detector, m) {
m.doc() = R"pbdoc(
C/C++ API
@ -29,7 +31,9 @@ PYBIND11_MODULE(_sls_detector, m) {
)pbdoc";
init_enums(m);
init_experimental(m);
init_det(m);
init_network(m);
// init_experimental(m);
py::module io = m.def_submodule("io", "Submodule for io");

39
python/src/network.cpp Normal file
View File

@ -0,0 +1,39 @@
/*
This file contains Python bindings for the IpAddr and MacAddr
classes.
*/
#include <pybind11/chrono.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "network_utils.h"
namespace py = pybind11;
using sls::IpAddr;
using sls::MacAddr;
void init_network(py::module &m) {
py::class_ <IpAddr> IpAddr(m, "IpAddr");
IpAddr.def(py::init())
.def(py::init<const std::string&>())
.def(py::init<uint32_t>())
.def("hex", &IpAddr::hex)
.def("uint32", &IpAddr::uint32)
.def(py::self == py::self)
.def("__repr__", &IpAddr::str)
.def("str", &IpAddr::str);
py::class_ <MacAddr> MacAddr(m, "MacAddr");
MacAddr.def(py::init())
.def(py::init<const std::string&>())
.def(py::init<uint64_t>())
.def("hex", &MacAddr::hex)
.def(py::self == py::self)
.def("uint64", &MacAddr::uint64)
.def("__repr__", &MacAddr::str)
.def("str", &MacAddr::str);
}

View File

@ -1,8 +1,13 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Testing parameters and methods of the Detector class using mocks
Testing the Detector python class by mocking calls.
Should only be used when there is functionality in
the detector.py file.
An example is converting a mask to a list of set bits.
"""
from unittest.mock import Mock
import pytest
from pytest_mock import mocker
@ -13,459 +18,471 @@ sys.path.append('/home/l_frojdh/slsdetectorgrup/sls_detector')
import _sls_detector
from sls_detector.errors import DetectorValueError, DetectorError
from sls_detector.utils import all_equal, element_if_equal
@pytest.fixture
def d():
from sls_detector import Detector
return Detector()
def test_length(d, mocker):
m = mocker.patch('sls_detector.Detector.size')
m.return_value = 5
assert(len(d) == 5)
def test_length_zero(d):
assert len(d) == 0
def test_counters_single(d, mocker):
m = mocker.patch('sls_detector.Detector.getCounterMask')
m.return_value = [7]
assert(d.counters == [0,1,2])
def test_acq_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.acq')
d.acq()
m.assert_called_once_with()
def test_busy_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getAcquiringFlag')
m.return_value = False
assert d.busy == False
def test_set_busy(d):
d.busy = True
assert d.busy == True
assert d._api.getAcquiringFlag() == True
d.busy = False
assert d.busy == False
assert d._api.getAcquiringFlag() == False
def test_error_mask(d):
d._api.setErrorMask(1)
assert d.error_mask == 1
d.clear_errors()
def test_error_handling(d):
with pytest.raises(DetectorError):
d._provoke_error()
def test_assign_to_detector_type(d):
with pytest.raises(AttributeError):
d.detector_type = 'Eiger'
def test_det_type(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDetectorType')
m.return_value = 'Eiger'
assert d.detector_type == 'Eiger'
def test_get_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getExposureTime')
m.return_value = 100000000
assert d.exposure_time == 0.1
def test_set_exposure_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setExposureTime')
d.exposure_time = 1.5
m.assert_called_once_with(1500000000)
def test_set_exposure_time_less_than_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setExposureTime')
with pytest.raises(DetectorValueError):
d.exposure_time = -7
def test_get_file_index(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFileIndex')
m.return_value = 8
assert d.file_index == 8
def test_set_file_index(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFileIndex')
d.file_index = 9
m.assert_called_with(9)
def file_index_with_no_detector(d):
assert d.file_index == -100
def dr_with_no_detector(d):
assert d.dynamic_range == -100
def test_set_file_index_raises_on_neg(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setFileIndex')
with pytest.raises(ValueError):
d.file_index = -9
def test_get_file_name(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFileName')
d.file_name
m.assert_called_once_with()
def test_set_file_name(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFileName')
d.file_name = 'hej'
m.assert_called_once_with('hej')
def test_get_file_path(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFilePath')
d.file_path
m.assert_called_once_with()
def test_set_file_path_when_path_exists(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFilePath')
#To avoid raising an exception because path is not there
mock_os = mocker.patch('os.path.exists')
mock_os.return_value = True
d.file_path = '/path/to/something/'
m.assert_called_once_with('/path/to/something/')
def test_set_file_path_raises_when_not_exists(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setFilePath')
mock_os = mocker.patch('os.path.exists')
mock_os.return_value = False
with pytest.raises(FileNotFoundError):
d.file_path = '/path/to/something/'
def test_get_file_write(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFileWrite')
m.return_value = False
assert d.file_write == False
def test_set_file_write(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setFileWrite')
d.file_write = True
m.assert_called_once_with(True)
def test_get_firmware_version(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getFirmwareVersion')
m.return_value = 20
assert d.firmware_version == 20
def test_cannot_set_fw_version(d):
with pytest.raises(AttributeError):
d.firmware_version = 20
def test_get_high_voltage_call_signature(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDac')
d.high_voltage
m.assert_called_once_with('vhighvoltage', -1)
def test_get_high_voltage(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDac')
m.return_value = 80
assert d.high_voltage == 80
#self._api.setDac('vhighvoltage', -1, voltage)
def test_set_high_voltage(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDac')
d.high_voltage = 80
m.assert_called_once_with('vhighvoltage', -1, 80)
def test_decode_hostname_two_names(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getHostname')
m.return_value = 'beb059+beb048+'
assert d.hostname == ['beb059', 'beb048']
def test_decode_hostname_four_names(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getHostname')
m.return_value = 'beb059+beb048+beb120+beb153+'
assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153']
def test_decode_hostname_blank(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getHostname')
m.return_value = ''
assert d.hostname == []
def test_get_image_size_gives_correct_size(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getImageSize')
m.return_value = (512,1024)
im_size = d.image_size
assert im_size.rows == 512
assert im_size.cols == 1024
def test_load_config(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.readConfigurationFile')
#To avoid raising an exception because path is not there
mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = True
d.load_config('/path/to/my/file.config')
m.assert_called_once_with('/path/to/my/file.config')
def test_load_config_raises_when_file_is_not_found(d, mocker):
mocker.patch('_sls_detector.DetectorApi.readConfigurationFile')
mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = False
with pytest.raises(FileNotFoundError):
d.load_config('/path/to/my/file.config')
def test_load_parameters(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.readParametersFile')
#To avoid raising an exception because path is not there
mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = True
d.load_parameters('/path/to/my/file.par')
m.assert_called_once_with('/path/to/my/file.par')
def test_load_parameters_raises_when_file_is_not_found(d, mocker):
mocker.patch('_sls_detector.DetectorApi.readParametersFile')
mock_os = mocker.patch('os.path.isfile')
mock_os.return_value = False
with pytest.raises(FileNotFoundError):
d.load_parameters('/path/to/my/file.par')
#getDetectorGeometry
def test_get_module_geometry_gives_correct_size(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry')
m.return_value = (13,7)
g = d.module_geometry
assert g.vertical == 7
assert g.horizontal == 13
def test_get_module_geometry_access(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry')
m.return_value = (12,3)
assert d.module_geometry[0] == 12
assert d.module_geometry[1] == 3
assert d.module_geometry.vertical == 3
assert d.module_geometry.horizontal == 12
def test_module_geometry_without_detectors(d):
t = d.module_geometry
assert t.horizontal == 0
assert t.vertical == 0
def test_get_n_frames(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNumberOfFrames')
m.return_value = 3
assert d.n_frames == 3
def test_set_n_frames(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames')
d.n_frames = 9
m.assert_called_once_with(9)
def test_nframes_without_detector(d):
assert d.n_frames == -100
def test_set_n_frames_raises_on_neg(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames')
with pytest.raises(DetectorValueError):
d.n_frames = -1
def test_set_n_frames_raises_on_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames')
with pytest.raises(DetectorValueError):
d.n_frames = 0
def test_n_cycles_without_detector(d):
assert d.n_cycles == -100
def test_set_n_cycles_raises_on_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setCycles')
with pytest.raises(DetectorValueError):
d.n_cycles = 0
def test_set_n_cycles(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setCycles')
d.n_cycles = 56
m.assert_called_once_with(56)
def test_n_measurements_without_detector(d):
assert d.n_measurements == -100
def test_set_n_measurements_raises_on_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements')
with pytest.raises(DetectorValueError):
d.n_measurements = 0
def test_set_n_measurements(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements')
d.n_measurements = 560
m.assert_called_once_with(560)
def test_get_n_modules_no_detector(d):
assert d.n_modules == 0
def test_get_n_modules(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors')
m.return_value = 12
assert d.n_modules == 12
def test_get_period_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getPeriod')
m.return_value = 130000000
assert d.period == 0.13
def test_set_period_time(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setPeriod')
d.period = 1.953
m.assert_called_once_with(1953000000)
def test_set_period_time_less_than_zero(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setPeriod')
with pytest.raises(ValueError):
d.period = -7
def test_get_online(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getOnline')
d.online
m.assert_called_once_with()
def test_set_online(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setOnline')
d.online = True
m.assert_called_once_with(True)
def test_last_client_ip_no_detector(d):
assert d.last_client_ip == ''
def test_last_cliten_ip_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getLastClientIP')
d.last_client_ip
m.assert_called_once_with()
#-------------------------------------------------------------Rate correction
def test_get_rate_correction(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getRateCorrection')
m.return_value = [132,129]
assert d.rate_correction == [132,129]
def test_set_rate_correction(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setRateCorrection')
mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors')
mock_n.return_value = 3
d.rate_correction = [123,90,50]
m.assert_called_once_with([123,90,50])
def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker):
mocker.patch('_sls_detector.DetectorApi.setRateCorrection')
mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors')
mock_n.return_value = 4
with pytest.raises(ValueError):
d.rate_correction = [123,90,50]
#----------------------------------------------------------------Readout clock
def test_get_readout_clock_0(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
m.return_value = 0
assert d.readout_clock == 'Full Speed'
def test_get_readout_clock_1(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
m.return_value = 1
assert d.readout_clock == 'Half Speed'
def test_get_readout_clock_2(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
m.return_value = 2
assert d.readout_clock == 'Quarter Speed'
def test_get_readout_clock_3(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
m.return_value = 3
assert d.readout_clock == 'Super Slow Speed'
def test_set_readout_clock_0(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Full Speed'
m.assert_called_once_with(0)
def test_set_readout_clock_1(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Half Speed'
m.assert_called_once_with(1)
def test_set_readout_clock_2(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Quarter Speed'
m.assert_called_once_with(2)
def test_set_readout_clock_3(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
d.readout_clock = 'Super Slow Speed'
m.assert_called_once_with(3)
#----------------------------------------------------------------rx_datastream
def test_get_rx_datastream(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getRxDataStreamStatus')
m.return_value = False
assert d.rx_datastream == False
def test_set_rx_datastream(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setRxDataStreamStatus')
d.rx_datastream = True
m.assert_called_once_with(True)
def test_get_rx_zmqip(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
d.rx_zmqip
m.assert_called_once_with('rx_zmqip')
def test_get_rx_zmqport_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
d.rx_zmqport
m.assert_called_once_with('rx_zmqport')
def test_get_rx_zmqport_decode(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
m.return_value = ['30001', '30003']
assert d.rx_zmqport == [30001, 30003]
def test_get_rx_zmqport_empty(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
m.return_value = ''
assert d.rx_zmqport == []
#--------------------------------------------------------------------status
def test_status_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getRunStatus')
d.status
m.assert_called_once_with()
def test_start_detecor(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.startAcquisition')
d.start_detector()
m.assert_called_once_with()
def test_stop_acq_call(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.stopAcquisition')
d.stop_detector()
m.assert_called_once_with()
#------------------------------------------------------------------timing mode
def test_get_timing_mode(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getTimingMode')
d.timing_mode
m.assert_called_once_with()
def test_set_timing_mode(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setTimingMode')
d.timing_mode = 'auto'
m.assert_called_once_with('auto')
#----------------------------------------------------------------vthreshold
def test_get_vthreshold(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.getDac')
d.vthreshold
m.assert_called_once_with('vthreshold', -1)
def test_set_vthreshold(d, mocker):
m = mocker.patch('_sls_detector.DetectorApi.setDac')
d.vthreshold = 1675
m.assert_called_once_with('vthreshold', -1, 1675)
def test_counters_multi(d, mocker):
m = mocker.patch('sls_detector.Detector.getCounterMask')
m.return_value = [7, 9]
assert(d.counters == [[0,1,2],[0,3]])
def test_set_counters_single(d, mocker):
m = mocker.patch('sls_detector.Detector.setCounterMask')
d.counters = [0,2]
m.assert_called_once_with(5)
# def test_busy_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getAcquiringFlag')
# m.return_value = False
# assert d.busy == False
# def test_set_busy(d):
# d.busy = True
# assert d.busy == True
# assert d._api.getAcquiringFlag() == True
# d.busy = False
# assert d.busy == False
# assert d._api.getAcquiringFlag() == False
# def test_error_mask(d):
# d._api.setErrorMask(1)
# assert d.error_mask == 1
# d.clear_errors()
# def test_error_handling(d):
# with pytest.raises(DetectorError):
# d._provoke_error()
# def test_assign_to_detector_type(d):
# with pytest.raises(AttributeError):
# d.detector_type = 'Eiger'
# def test_det_type(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDetectorType')
# m.return_value = 'Eiger'
# assert d.detector_type == 'Eiger'
# def test_get_exposure_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getExposureTime')
# m.return_value = 100000000
# assert d.exposure_time == 0.1
# def test_set_exposure_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setExposureTime')
# d.exposure_time = 1.5
# m.assert_called_once_with(1500000000)
# def test_set_exposure_time_less_than_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setExposureTime')
# with pytest.raises(DetectorValueError):
# d.exposure_time = -7
# def test_get_file_index(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFileIndex')
# m.return_value = 8
# assert d.file_index == 8
# def test_set_file_index(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFileIndex')
# d.file_index = 9
# m.assert_called_with(9)
# def file_index_with_no_detector(d):
# assert d.file_index == -100
# def dr_with_no_detector(d):
# assert d.dynamic_range == -100
# def test_set_file_index_raises_on_neg(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setFileIndex')
# with pytest.raises(ValueError):
# d.file_index = -9
# def test_get_file_name(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFileName')
# d.file_name
# m.assert_called_once_with()
# def test_set_file_name(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFileName')
# d.file_name = 'hej'
# m.assert_called_once_with('hej')
# def test_get_file_path(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFilePath')
# d.file_path
# m.assert_called_once_with()
# def test_set_file_path_when_path_exists(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFilePath')
# #To avoid raising an exception because path is not there
# mock_os = mocker.patch('os.path.exists')
# mock_os.return_value = True
# d.file_path = '/path/to/something/'
# m.assert_called_once_with('/path/to/something/')
# def test_set_file_path_raises_when_not_exists(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setFilePath')
# mock_os = mocker.patch('os.path.exists')
# mock_os.return_value = False
# with pytest.raises(FileNotFoundError):
# d.file_path = '/path/to/something/'
# def test_get_file_write(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFileWrite')
# m.return_value = False
# assert d.file_write == False
# def test_set_file_write(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setFileWrite')
# d.file_write = True
# m.assert_called_once_with(True)
# def test_get_firmware_version(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getFirmwareVersion')
# m.return_value = 20
# assert d.firmware_version == 20
# def test_cannot_set_fw_version(d):
# with pytest.raises(AttributeError):
# d.firmware_version = 20
# def test_get_high_voltage_call_signature(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDac')
# d.high_voltage
# m.assert_called_once_with('vhighvoltage', -1)
# def test_get_high_voltage(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDac')
# m.return_value = 80
# assert d.high_voltage == 80
# #self._api.setDac('vhighvoltage', -1, voltage)
# def test_set_high_voltage(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setDac')
# d.high_voltage = 80
# m.assert_called_once_with('vhighvoltage', -1, 80)
# def test_decode_hostname_two_names(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getHostname')
# m.return_value = 'beb059+beb048+'
# assert d.hostname == ['beb059', 'beb048']
# def test_decode_hostname_four_names(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getHostname')
# m.return_value = 'beb059+beb048+beb120+beb153+'
# assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153']
# def test_decode_hostname_blank(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getHostname')
# m.return_value = ''
# assert d.hostname == []
# def test_get_image_size_gives_correct_size(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getImageSize')
# m.return_value = (512,1024)
# im_size = d.image_size
# assert im_size.rows == 512
# assert im_size.cols == 1024
# def test_load_config(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.readConfigurationFile')
# #To avoid raising an exception because path is not there
# mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = True
# d.load_config('/path/to/my/file.config')
# m.assert_called_once_with('/path/to/my/file.config')
# def test_load_config_raises_when_file_is_not_found(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.readConfigurationFile')
# mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = False
# with pytest.raises(FileNotFoundError):
# d.load_config('/path/to/my/file.config')
# def test_load_parameters(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.readParametersFile')
# #To avoid raising an exception because path is not there
# mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = True
# d.load_parameters('/path/to/my/file.par')
# m.assert_called_once_with('/path/to/my/file.par')
# def test_load_parameters_raises_when_file_is_not_found(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.readParametersFile')
# mock_os = mocker.patch('os.path.isfile')
# mock_os.return_value = False
# with pytest.raises(FileNotFoundError):
# d.load_parameters('/path/to/my/file.par')
# #getDetectorGeometry
# def test_get_module_geometry_gives_correct_size(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry')
# m.return_value = (13,7)
# g = d.module_geometry
# assert g.vertical == 7
# assert g.horizontal == 13
# def test_get_module_geometry_access(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry')
# m.return_value = (12,3)
# assert d.module_geometry[0] == 12
# assert d.module_geometry[1] == 3
# assert d.module_geometry.vertical == 3
# assert d.module_geometry.horizontal == 12
# def test_module_geometry_without_detectors(d):
# t = d.module_geometry
# assert t.horizontal == 0
# assert t.vertical == 0
# def test_get_n_frames(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNumberOfFrames')
# m.return_value = 3
# assert d.n_frames == 3
# def test_set_n_frames(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames')
# d.n_frames = 9
# m.assert_called_once_with(9)
# def test_nframes_without_detector(d):
# assert d.n_frames == -100
# def test_set_n_frames_raises_on_neg(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames')
# with pytest.raises(DetectorValueError):
# d.n_frames = -1
# def test_set_n_frames_raises_on_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames')
# with pytest.raises(DetectorValueError):
# d.n_frames = 0
# def test_n_cycles_without_detector(d):
# assert d.n_cycles == -100
# def test_set_n_cycles_raises_on_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setCycles')
# with pytest.raises(DetectorValueError):
# d.n_cycles = 0
# def test_set_n_cycles(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setCycles')
# d.n_cycles = 56
# m.assert_called_once_with(56)
# def test_n_measurements_without_detector(d):
# assert d.n_measurements == -100
# def test_set_n_measurements_raises_on_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements')
# with pytest.raises(DetectorValueError):
# d.n_measurements = 0
# def test_set_n_measurements(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements')
# d.n_measurements = 560
# m.assert_called_once_with(560)
# def test_get_n_modules_no_detector(d):
# assert d.n_modules == 0
# def test_get_n_modules(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors')
# m.return_value = 12
# assert d.n_modules == 12
# def test_get_period_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getPeriod')
# m.return_value = 130000000
# assert d.period == 0.13
# def test_set_period_time(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setPeriod')
# d.period = 1.953
# m.assert_called_once_with(1953000000)
# def test_set_period_time_less_than_zero(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setPeriod')
# with pytest.raises(ValueError):
# d.period = -7
# def test_get_online(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getOnline')
# d.online
# m.assert_called_once_with()
# def test_set_online(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setOnline')
# d.online = True
# m.assert_called_once_with(True)
# def test_last_client_ip_no_detector(d):
# assert d.last_client_ip == ''
# def test_last_cliten_ip_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getLastClientIP')
# d.last_client_ip
# m.assert_called_once_with()
# #-------------------------------------------------------------Rate correction
# def test_get_rate_correction(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getRateCorrection')
# m.return_value = [132,129]
# assert d.rate_correction == [132,129]
# def test_set_rate_correction(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setRateCorrection')
# mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors')
# mock_n.return_value = 3
# d.rate_correction = [123,90,50]
# m.assert_called_once_with([123,90,50])
# def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker):
# mocker.patch('_sls_detector.DetectorApi.setRateCorrection')
# mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors')
# mock_n.return_value = 4
# with pytest.raises(ValueError):
# d.rate_correction = [123,90,50]
# #----------------------------------------------------------------Readout clock
# def test_get_readout_clock_0(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
# m.return_value = 0
# assert d.readout_clock == 'Full Speed'
# def test_get_readout_clock_1(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
# m.return_value = 1
# assert d.readout_clock == 'Half Speed'
# def test_get_readout_clock_2(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
# m.return_value = 2
# assert d.readout_clock == 'Quarter Speed'
# def test_get_readout_clock_3(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed')
# m.return_value = 3
# assert d.readout_clock == 'Super Slow Speed'
# def test_set_readout_clock_0(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Full Speed'
# m.assert_called_once_with(0)
# def test_set_readout_clock_1(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Half Speed'
# m.assert_called_once_with(1)
# def test_set_readout_clock_2(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Quarter Speed'
# m.assert_called_once_with(2)
# def test_set_readout_clock_3(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed')
# d.readout_clock = 'Super Slow Speed'
# m.assert_called_once_with(3)
# #----------------------------------------------------------------rx_datastream
# def test_get_rx_datastream(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getRxDataStreamStatus')
# m.return_value = False
# assert d.rx_datastream == False
# def test_set_rx_datastream(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setRxDataStreamStatus')
# d.rx_datastream = True
# m.assert_called_once_with(True)
# def test_get_rx_zmqip(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
# d.rx_zmqip
# m.assert_called_once_with('rx_zmqip')
# def test_get_rx_zmqport_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
# d.rx_zmqport
# m.assert_called_once_with('rx_zmqport')
# def test_get_rx_zmqport_decode(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
# m.return_value = ['30001', '30003']
# assert d.rx_zmqport == [30001, 30003]
# def test_get_rx_zmqport_empty(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter')
# m.return_value = ''
# assert d.rx_zmqport == []
# #--------------------------------------------------------------------status
# def test_status_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getRunStatus')
# d.status
# m.assert_called_once_with()
# def test_start_detecor(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.startAcquisition')
# d.start_detector()
# m.assert_called_once_with()
# def test_stop_acq_call(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.stopAcquisition')
# d.stop_detector()
# m.assert_called_once_with()
# #------------------------------------------------------------------timing mode
# def test_get_timing_mode(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getTimingMode')
# d.timing_mode
# m.assert_called_once_with()
# def test_set_timing_mode(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setTimingMode')
# d.timing_mode = 'auto'
# m.assert_called_once_with('auto')
# #----------------------------------------------------------------vthreshold
# def test_get_vthreshold(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.getDac')
# d.vthreshold
# m.assert_called_once_with('vthreshold', -1)
# def test_set_vthreshold(d, mocker):
# m = mocker.patch('_sls_detector.DetectorApi.setDac')
# d.vthreshold = 1675
# m.assert_called_once_with('vthreshold', -1, 1675)

View File

@ -1,12 +1,12 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Testing parameters and methods of the Detector class using mocks
Testing functions from utils.py
"""
import pytest
from sls_detector.utils import eiger_register_to_time
from sls_detector.utils import all_equal, element_if_equal
from sls_detector.utils import *
def test_convert_zero():
assert eiger_register_to_time(0) == 0
@ -47,4 +47,16 @@ def test_element_if_equal_str():
assert element_if_equal('hhh') == 'h'
def test_element_if_equal_int_fails():
assert element_if_equal([5, 6, 7]) == [5, 6, 7]
assert element_if_equal([5, 6, 7]) == [5, 6, 7]
def test_get_set_bits():
assert(get_set_bits(0) == [])
assert get_set_bits(7) == [0, 1, 2]
def test_list_to_mask():
assert(list_to_bitmask([0,1,2]) == 7)
assert(list_to_bitmask([]) == 0)
assert(list_to_bitmask([0]) == 1)
assert(list_to_bitmask([1]) == 2)
assert(list_to_bitmask([3]) == 8)
assert(list_to_bitmask([1,1,1]) == 2)

View File

@ -497,14 +497,14 @@
#define PATTERN_WAIT_TIMER_2_LSB_REG (0x76 << MEM_MAP_SHIFT)
#define PATTERN_WAIT_TIMER_2_MSB_REG (0x77 << MEM_MAP_SHIFT)
/* ADC Disable RW register TODO */
#define ADC_DISABLE_REG (0x78 << MEM_MAP_SHIFT)
/* Readout enable RW register */
#define READOUT_10G_ENABLE_REG (0x79 << MEM_MAP_SHIFT)
/* DAC Value RW register TODO */
//#define DAC_VALUE_REG (0x79 << MEM_MAP_SHIFT)
#define READOUT_10G_ENABLE_ANLG_OFST (0)
#define READOUT_10G_ENABLE_ANLG_MSK (0x000000FF << READOUT_10G_ENABLE_ANLG_OFST)
#define READOUT_10G_ENABLE_DGTL_OFST (8)
#define READOUT_10G_ENABLE_DGTL_MSK (0x00000001 << READOUT_10G_ENABLE_DGTL_OFST)
/* DAC Number RW register TODO */
//#define DAC_NUMBER_REG (0x7A << MEM_MAP_SHIFT)
/* Digital Bit External Trigger RW register */
#define DBIT_EXT_TRG_REG (0x7B << MEM_MAP_SHIFT)
@ -548,9 +548,8 @@
#define I2C_SDA_HOLD_REG (0x10A << MEM_MAP_SHIFT)
//fixme: upto 0x10f
/* Round Robin */
#define RXR_ENDPOINT_START_REG (0x1000 << MEM_MAP_SHIFT)

View File

@ -41,6 +41,7 @@ int virtual_status = 0;
int virtual_stop = 0;
#endif
// 1g readout
int dataBytes = 0;
int analogDataBytes = 0;
int digitalDataBytes = 0;
@ -48,18 +49,19 @@ char* analogData = 0;
char* digitalData = 0;
char volatile *analogDataPtr = 0;
char volatile *digitalDataPtr = 0;
char udpPacketData[UDP_PACKET_DATA_BYTES + sizeof(sls_detector_header)];
uint32_t adcEnableMask_1g = 0;
// 10g readout
uint8_t adcEnableMask_10g = 0;
int32_t clkPhase[NUM_CLOCKS] = {0, 0, 0, 0};
uint32_t clkFrequency[NUM_CLOCKS] = {40, 20, 20, 200};
int dacValues[NDAC] = {0};
// software limit that depends on the current chip on the ctb
int vLimit = 0;
int highvoltage = 0;
uint32_t adcEnableMask = 0;
int analogEnable = 1;
int digitalEnable = 0;
int naSamples = 1;
@ -459,7 +461,8 @@ void setupDetector() {
}
vLimit = DEFAULT_VLIMIT;
highvoltage = 0;
adcEnableMask = BIT_32_MSK;
adcEnableMask_1g = 0;
adcEnableMask_10g = 0;
analogEnable = 1;
digitalEnable = 0;
naSamples = 1;
@ -533,22 +536,22 @@ void setupDetector() {
setPeriod(DEFAULT_PERIOD);
setDelayAfterTrigger(DEFAULT_DELAY);
setTiming(DEFAULT_TIMING_MODE);
setReadoutMode(ANALOG_ONLY);
// enable all ADC channels
setADCEnableMask(BIT_32_MSK);
setADCEnableMask(BIT32_MSK);
setADCEnableMask_10G(BIT32_MSK);
if (setReadoutMode(ANALOG_ONLY) == FAIL) {
strcpy(initErrorMessage,
"Could not set readout mode to analog only.\n");
FILE_LOG(logERROR, ("%s\n\n", initErrorMessage));
initError = FAIL;
}
}
int allocateRAM() {
int updateDatabytesandAllocateRAM() {
int oldAnalogDataBytes = analogDataBytes;
int oldDigitalDataBytes = digitalDataBytes;
updateDataBytes();
// only allcoate RAM for 1 giga udp (if 10G, return)
if (enableTenGigabitEthernet(-1))
return OK;
// update only if change in databytes
if (analogDataBytes == oldAnalogDataBytes && digitalDataBytes == oldDigitalDataBytes) {
FILE_LOG(logDEBUG1, ("RAM size (Analog:%d, Digital:%d) already allocated. Nothing to be done.\n",
@ -602,12 +605,12 @@ void updateDataBytes() {
// analog
if (analogEnable) {
if (adcEnableMask == BIT_32_MSK)
if (adcEnableMask_1g == BIT32_MSK)
nachans = 32;
else {
int ichan = 0;
for (ichan = 0; ichan < NCHAN_ANALOG; ++ichan) {
if (adcEnableMask & (1 << ichan))
if (adcEnableMask_1g & (1 << ichan))
++nachans;
}
}
@ -666,23 +669,72 @@ int setDynamicRange(int dr){
}
int setADCEnableMask(uint32_t mask) {
FILE_LOG(logINFO, ("Setting adcEnableMask to 0x%08x\n", mask));
adcEnableMask = mask;
// get disable mask
mask ^= BIT_32_MSK;
bus_w(ADC_DISABLE_REG, mask);
// update databytes and allocate ram
return allocateRAM();
if (mask == 0u) {
FILE_LOG(logERROR, ("Cannot set 1gb adc mask to 0\n"));
return FAIL;
}
FILE_LOG(logINFO, ("Setting adcEnableMask 1G to 0x%08x\n", mask));
adcEnableMask_1g = mask;
// 1Gb enabled
if (!enableTenGigabitEthernet(-1)) {
if (updateDatabytesandAllocateRAM() == FAIL) {
return FAIL;
}
}
return OK;
}
uint32_t getADCEnableMask() {
uint32_t retval = bus_r(ADC_DISABLE_REG);
return adcEnableMask_1g;
}
// get enable mask
retval ^= BIT_32_MSK;
adcEnableMask = retval;
void setADCEnableMask_10G(uint32_t mask) {
if (mask == 0u) {
FILE_LOG(logERROR, ("Cannot set 10gb adc mask to 0\n"));
return;
}
// convert 32 bit mask to 8 bit mask
uint8_t actualMask = 0;
if (mask != 0) {
int ival = 0;
int ich = 0;
for (ich = 0; ich < NCHAN_ANALOG; ich = ich + 4) {
if ((1 << ich) & mask) {
actualMask |= (1 << ival);
}
++ival;
}
}
FILE_LOG(logINFO, ("Setting adcEnableMask 10G to 0x%x (from 0x%08x)\n", actualMask, mask));
adcEnableMask_10g = actualMask;
if (analogEnable) {
uint32_t addr = READOUT_10G_ENABLE_REG;
bus_w(addr, bus_r(addr) & (~READOUT_10G_ENABLE_ANLG_MSK));
bus_w(addr, bus_r(addr) | ((adcEnableMask_10g << READOUT_10G_ENABLE_ANLG_OFST) & READOUT_10G_ENABLE_ANLG_MSK));
}
}
uint32_t getADCEnableMask_10G() {
if (analogEnable) {
adcEnableMask_10g = ((bus_r(READOUT_10G_ENABLE_REG) & READOUT_10G_ENABLE_ANLG_MSK) >> READOUT_10G_ENABLE_ANLG_OFST);
}
// convert 8 bit mask to 32 bit mask
uint32_t retval = 0;
if (adcEnableMask_10g) {
int ival = 0;
int iloop = 0;
for (ival = 0; ival < 8; ++ival) {
// if bit in 8 bit mask set
if ((1 << ival) & adcEnableMask_10g) {
// set it for 4 bits in 32 bit mask
for (iloop = 0; iloop < 4; ++iloop) {
retval |= (1 << (ival * 4 + iloop));
}
}
}
}
return retval;
}
@ -722,31 +774,61 @@ int setExternalSampling(int val) {
/* parameters - readout */
int setReadoutMode(enum readoutMode mode) {
uint32_t addr = CONFIG_REG;
analogEnable = 0;
digitalEnable = 0;
switch(mode) {
case ANALOG_ONLY:
FILE_LOG(logINFO, ("Setting Analog Only Readout\n"));
bus_w(addr, bus_r(addr) & (~CONFIG_DSBL_ANLG_OTPT_MSK) & (~CONFIG_ENBLE_DGTL_OTPT_MSK));
analogEnable = 1;
break;
case DIGITAL_ONLY:
FILE_LOG(logINFO, ("Setting Digital Only Readout\n"));
bus_w(addr, bus_r(addr) | CONFIG_DSBL_ANLG_OTPT_MSK | CONFIG_ENBLE_DGTL_OTPT_MSK);
digitalEnable = 1;
break;
case ANALOG_AND_DIGITAL:
FILE_LOG(logINFO, ("Setting Analog & Digital Readout\n"));
bus_w(addr, (bus_r(addr) & (~CONFIG_DSBL_ANLG_OTPT_MSK)) | CONFIG_ENBLE_DGTL_OTPT_MSK);
analogEnable = 1;
digitalEnable = 1;
break;
default:
FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", mode));
return FAIL;
}
uint32_t regval = bus_r(addr);
analogEnable = (((regval & CONFIG_DSBL_ANLG_OTPT_MSK) >> CONFIG_DSBL_ANLG_OTPT_OFST) ? 0 : 1);
digitalEnable = ((regval & CONFIG_ENBLE_DGTL_OTPT_MSK) >> CONFIG_ENBLE_DGTL_OTPT_OFST);
// update databytes and allocate ram
if (allocateRAM() == FAIL) {
return FAIL;
uint32_t addr = CONFIG_REG;
uint32_t addr_readout_10g = READOUT_10G_ENABLE_REG;
// default: analog only
bus_w(addr, bus_r(addr) & (~CONFIG_DSBL_ANLG_OTPT_MSK) & (~CONFIG_ENBLE_DGTL_OTPT_MSK));
bus_w(addr_readout_10g, bus_r(addr_readout_10g) & (~READOUT_10G_ENABLE_ANLG_MSK) & ~(READOUT_10G_ENABLE_DGTL_MSK));
bus_w(addr_readout_10g, bus_r(addr_readout_10g) | ((adcEnableMask_10g << READOUT_10G_ENABLE_ANLG_OFST) & READOUT_10G_ENABLE_ANLG_MSK));
// disable analog (digital only)
if (!analogEnable) {
bus_w(addr, bus_r(addr) | CONFIG_DSBL_ANLG_OTPT_MSK);
bus_w(addr_readout_10g, bus_r(addr_readout_10g) & (~READOUT_10G_ENABLE_ANLG_MSK));
}
// enable digital (analog and digital)
if (digitalEnable) {
bus_w(addr, bus_r(addr) | CONFIG_ENBLE_DGTL_OTPT_MSK);
bus_w(addr_readout_10g, bus_r(addr_readout_10g) | READOUT_10G_ENABLE_DGTL_MSK);
}
// 1Gb
if (!enableTenGigabitEthernet(-1)) {
if (updateDatabytesandAllocateRAM() == FAIL) {
return FAIL;
}
}
// 10Gb
else {
// validate adcenablemask for 10g
if (analogEnable && adcEnableMask_10g != ((bus_r(READOUT_10G_ENABLE_REG) & READOUT_10G_ENABLE_ANLG_MSK) >> READOUT_10G_ENABLE_ANLG_OFST)) {
FILE_LOG(logERROR, ("Setting readout mode failed. Could not set 10g adc enable mask to 0x%x\n.", adcEnableMask_10g));
return FAIL;
}
}
return OK;
}
@ -800,8 +882,12 @@ int setNumAnalogSamples(int val) {
naSamples = val;
bus_w(SAMPLES_REG, bus_r(SAMPLES_REG) &~ SAMPLES_ANALOG_MSK);
bus_w(SAMPLES_REG, bus_r(SAMPLES_REG) | ((val << SAMPLES_ANALOG_OFST) & SAMPLES_ANALOG_MSK));
if (allocateRAM() == FAIL) {
return FAIL;
// 1Gb
if (!enableTenGigabitEthernet(-1)) {
if (updateDatabytesandAllocateRAM() == FAIL) {
return FAIL;
}
}
return OK;
}
@ -819,8 +905,11 @@ int setNumDigitalSamples(int val) {
ndSamples = val;
bus_w(SAMPLES_REG, bus_r(SAMPLES_REG) &~ SAMPLES_DIGITAL_MSK);
bus_w(SAMPLES_REG, bus_r(SAMPLES_REG) | ((val << SAMPLES_DIGITAL_OFST) & SAMPLES_DIGITAL_MSK));
if (allocateRAM() == FAIL) {
return FAIL;
// 1Gb
if (!enableTenGigabitEthernet(-1)) {
if (updateDatabytesandAllocateRAM() == FAIL) {
return FAIL;
}
}
return OK;
}
@ -1359,42 +1448,39 @@ enum timingMode getTiming() {
/* configure mac */
long int calcChecksum(int sourceip, int destip) {
ip_header ip;
ip.ip_ver = 0x4;
ip.ip_ihl = 0x5;
ip.ip_tos = 0x0;
ip.ip_len = IP_PACKETSIZE;
ip.ip_ident = 0x0000;
ip.ip_flag = 0x2; //not nibble aligned (flag& offset
ip.ip_offset = 0x000;
ip.ip_ttl = 0x40;
ip.ip_protocol = 0x11;
ip.ip_chksum = 0x0000 ; // pseudo
ip.ip_sourceip = sourceip;
ip.ip_destip = destip;
int count = sizeof(ip);
unsigned short *addr;
addr = (unsigned short*) &(ip); /* warning: assignment from incompatible pointer type */
void calcChecksum(udp_header* udp) {
int count = IP_HEADER_SIZE;
long int sum = 0;
while( count > 1 ) {
// start at ip_tos as the memory is not continous for ip header
uint16_t *addr = (uint16_t*) (&(udp->ip_tos));
sum += *addr++;
count -= 2;
// ignore ethertype (from udp header)
addr++;
// from identification to srcip_lsb
while( count > 2 ) {
sum += *addr++;
count -= 2;
}
// ignore src udp port (from udp header)
addr++;
if (count > 0)
sum += *addr; // Add left-over byte, if any
while (sum>>16)
while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits
long int checksum = (~sum) & 0xffff;
FILE_LOG(logINFO, ("IP checksum is 0x%lx\n",checksum));
return checksum;
long int checksum = sum & 0xffff;
checksum += UDP_IP_HEADER_LENGTH_BYTES;
FILE_LOG(logINFO, ("\tIP checksum is 0x%lx\n",checksum));
udp->ip_checksum = checksum;
}
int configureMAC(){
uint32_t sourceip = udpDetails.srcip;
uint32_t destip = udpDetails.dstip;
@ -1409,8 +1495,7 @@ int configureMAC(){
// 1 giga udp
if (!enableTenGigabitEthernet(-1)) {
FILE_LOG(logINFOBLUE, ("Configuring 1G MAC\n"));
// if it was in 10G mode, it was not allocating RAM
if (allocateRAM() == FAIL)
if (updateDatabytesandAllocateRAM() == FAIL)
return -1;
char cDestIp[MAX_STR_LENGTH];
memset(cDestIp, 0, MAX_STR_LENGTH);
@ -1450,35 +1535,40 @@ int configureMAC(){
(long long unsigned int)destmac));
FILE_LOG(logINFO, ("\tDest. Port : %d \t\t\t(0x%08x)\n",destport, destport));
long int checksum=calcChecksum(sourceip, destip);
bus_w(TX_IP_REG, sourceip);
bus_w(RX_IP_REG, destip);
// start addr
uint32_t addr = RXR_ENDPOINT_START_REG;
// get struct memory
udp_header *udp = (udp_header*) (Blackfin_getBaseAddress() + addr / 2);
memset(udp, 0, sizeof(udp_header));
uint32_t val = 0;
// mac addresses
// msb (32) + lsb (16)
udp->udp_destmac_msb = ((destmac >> 16) & BIT32_MASK);
udp->udp_destmac_lsb = ((destmac >> 0) & BIT16_MASK);
// msb (16) + lsb (32)
udp->udp_srcmac_msb = ((sourcemac >> 32) & BIT16_MASK);
udp->udp_srcmac_lsb = ((sourcemac >> 0) & BIT32_MASK);
val = ((sourcemac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK);
bus_w(TX_MAC_LSB_REG, val);
FILE_LOG(logDEBUG1, ("Read from TX_MAC_LSB_REG: 0x%08x\n", bus_r(TX_MAC_LSB_REG)));
// ip addresses
udp->ip_srcip_msb = ((sourceip >> 16) & BIT16_MASK);
udp->ip_srcip_lsb = ((sourceip >> 0) & BIT16_MASK);
udp->ip_destip_msb = ((destip >> 16) & BIT16_MASK);
udp->ip_destip_lsb = ((destip >> 0) & BIT16_MASK);
val = ((sourcemac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK);
bus_w(TX_MAC_MSB_REG,val);
FILE_LOG(logDEBUG1, ("Read from TX_MAC_MSB_REG: 0x%08x\n", bus_r(TX_MAC_MSB_REG)));
// source port
udp->udp_srcport = sourceport;
udp->udp_destport = destport;
val = ((destmac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK);
bus_w(RX_MAC_LSB_REG, val);
FILE_LOG(logDEBUG1, ("Read from RX_MAC_LSB_REG: 0x%08x\n", bus_r(RX_MAC_LSB_REG)));
// other defines
udp->udp_ethertype = 0x800;
udp->ip_ver = 0x4;
udp->ip_ihl = 0x5;
udp->ip_flags = 0x2; //FIXME
udp->ip_ttl = 0x40;
udp->ip_protocol = 0x11;
// total length is redefined in firmware
val = ((destmac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK);
bus_w(RX_MAC_MSB_REG, val);
FILE_LOG(logDEBUG1, ("Read from RX_MAC_MSB_REG: 0x%08x\n", bus_r(RX_MAC_MSB_REG)));
val = (((sourceport << UDP_PORT_TX_OFST) & UDP_PORT_TX_MSK) |
((destport << UDP_PORT_RX_OFST) & UDP_PORT_RX_MSK));
bus_w(UDP_PORT_REG, val);
FILE_LOG(logDEBUG1, ("Read from UDP_PORT_REG: 0x%08x\n", bus_r(UDP_PORT_REG)));
bus_w(TX_IP_CHECKSUM_REG,(checksum << TX_IP_CHECKSUM_OFST) & TX_IP_CHECKSUM_MSK);
FILE_LOG(logDEBUG1, ("Read from TX_IP_CHECKSUM_REG: 0x%08x\n", bus_r(TX_IP_CHECKSUM_REG)));
calcChecksum(udp);
cleanFifos();//FIXME: resetPerpheral() for ctb?
resetPeripheral();
@ -2327,7 +2417,7 @@ void readSample(int ns) {
for (ich = 0; ich < NCHAN_ANALOG; ++ich) {
// if channel is in enable mask
if ((1 << ich) & (adcEnableMask)) {
if ((1 << ich) & (adcEnableMask_1g)) {
// unselect channel
bus_w(addr, bus_r(addr) & ~(DUMMY_FIFO_CHNNL_SLCT_MSK));

View File

@ -4,23 +4,36 @@
#define MIN_REQRD_VRSN_T_RD_API 0x181130
#define REQRD_FRMWR_VRSN 0x190821
#define REQRD_FRMWR_VRSN 0x191127
#define CTRL_SRVR_INIT_TIME_US (2 * 1000 * 1000)
/* Struct Definitions */
typedef struct ip_header_struct {
uint16_t ip_len;
uint8_t ip_tos;
uint8_t ip_ihl:4 ,ip_ver:4;
uint16_t ip_offset:13,ip_flag:3;
uint16_t ip_ident;
uint16_t ip_chksum;
uint8_t ip_protocol;
uint8_t ip_ttl;
uint32_t ip_sourceip;
uint32_t ip_destip;
} ip_header;
typedef struct udp_header_struct {
uint32_t udp_destmac_msb;
uint16_t udp_srcmac_msb;
uint16_t udp_destmac_lsb;
uint32_t udp_srcmac_lsb;
uint8_t ip_tos;
uint8_t ip_ihl: 4, ip_ver: 4;
uint16_t udp_ethertype;
uint16_t ip_identification;
uint16_t ip_totallength;
uint8_t ip_protocol;
uint8_t ip_ttl;
uint16_t ip_fragmentoffset: 13, ip_flags: 3;
uint16_t ip_srcip_msb;
uint16_t ip_checksum;
uint16_t ip_destip_msb;
uint16_t ip_srcip_lsb;
uint16_t udp_srcport;
uint16_t ip_destip_lsb;
uint16_t udp_checksum;
uint16_t udp_destport;
} udp_header;
#define IP_HEADER_SIZE (20)
#define UDP_IP_HEADER_LENGTH_BYTES (28)
/* Enums */
enum ADCINDEX {V_PWR_IO, V_PWR_A, V_PWR_B, V_PWR_C, V_PWR_D, I_PWR_IO, I_PWR_A, I_PWR_B, I_PWR_C, I_PWR_D};
@ -91,9 +104,9 @@ enum CLKINDEX {RUN_CLK, ADC_CLK, SYNC_CLK, DBIT_CLK, NUM_CLOCKS};
/* MSB & LSB DEFINES */
#define MSB_OF_64_BIT_REG_OFST (32)
#define LSB_OF_64_BIT_REG_OFST (0)
#define BIT_32_MSK (0xFFFFFFFF)
#define BIT32_MSK (0xFFFFFFFF)
#define BIT16_MASK (0xFFFF)
#define IP_PACKETSIZE (0x2032)
#define ADC_PORT_INVERT_VAL (0x453b2593)
#define MAXIMUM_ADC_CLK (65)
#define PLL_VCO_FREQ_MHZ (800)

View File

@ -674,7 +674,7 @@ int setSubExpTime(int64_t val) {
int64_t subdeadtime = eiger_virtual_subperiod * 10 -
eiger_virtual_subexptime * 10;
eiger_virtual_subexptime = (val / (10));
eiger_virtual_subperiod = (val + subdeadtime/10);
eiger_virtual_subperiod = (val + subdeadtime) /10;
#endif
return OK;
}

View File

@ -1326,7 +1326,7 @@ int configureMAC() {
FILE_LOG(logDEBUG1, ("\tWrite back released. MultiPurpose reg: 0x%x\n", bus_r(addr)));
FILE_LOG(logDEBUG1, ("\tConfiguring MAC CONF\n"));
mac_conf *mac_conf_regs = (mac_conf*)(Blackfin_getBaseAddress() + ENET_CONF_REG * 2); // direct write
mac_conf *mac_conf_regs = (mac_conf*)(Blackfin_getBaseAddress() + ENET_CONF_REG / 2); // direct write
mac_conf_regs->mac.mac_dest_mac1 = ((destmac >> (8 * 5)) & 0xFF);
mac_conf_regs->mac.mac_dest_mac2 = ((destmac >> (8 * 4)) & 0xFF);
mac_conf_regs->mac.mac_dest_mac3 = ((destmac >> (8 * 3)) & 0xFF);
@ -1364,7 +1364,7 @@ int configureMAC() {
mac_conf_regs->udp.udp_chksum = 0x0000;
FILE_LOG(logDEBUG1, ("\tConfiguring TSE\n"));
tse_conf *tse_conf_regs = (tse_conf*)(Blackfin_getBaseAddress() + TSE_CONF_REG * 2); // direct write
tse_conf *tse_conf_regs = (tse_conf*)(Blackfin_getBaseAddress() + TSE_CONF_REG / 2); // direct write
tse_conf_regs->rev = 0xA00;
tse_conf_regs->scratch = 0xCCCCCCCC;
tse_conf_regs->command_config = 0xB;

View File

@ -994,7 +994,7 @@ void setupHeader(int iRxEntry, enum interfaceType type, uint32_t destip, uint64_
// calculate rxr endpoint offset
addr += (iRxEntry * RXR_ENDPOINT_OFST);
// get struct memory
udp_header *udp = (udp_header*) (Blackfin_getBaseAddress() + addr * 2);
udp_header *udp = (udp_header*) (Blackfin_getBaseAddress() + addr / 2);
memset(udp, 0, sizeof(udp_header));
// mac addresses

View File

@ -33,7 +33,8 @@ typedef struct udp_header_struct {
uint16_t udp_destport;
} udp_header;
#define IP_HEADER_SIZE 20
#define IP_HEADER_SIZE (20)
#define UDP_IP_HEADER_LENGTH_BYTES (28)
/* Enums */
@ -93,7 +94,6 @@ enum CLKINDEX {RUN_CLK, ADC_CLK, NUM_CLOCKS};
#define MAX_PHASE_SHIFTS (160)
#define BIT16_MASK (0xFFFF)
#define UDP_IP_HEADER_LENGTH_BYTES (28)

View File

@ -82,7 +82,6 @@
/* Config RW regiseter */
#define CONFIG_REG (0x20 * REG_OFFSET + BASE_CONTROL)
#define CONFIG_COUNTER_ENA_OFST (0)
#define CONFIG_COUNTER_ENA_MSK (0x00000003 << CONFIG_COUNTER_ENA_OFST)
#define CONFIG_COUNTER_ENA_DEFAULT_VAL ((0x0 << CONFIG_COUNTER_ENA_OFST) & CONFIG_COUNTER_ENA_MSK)
@ -96,15 +95,13 @@
#define CONFIG_DYNAMIC_RANGE_16_VAL ((0x2 << CONFIG_DYNAMIC_RANGE_OFST) & CONFIG_DYNAMIC_RANGE_MSK)
#define CONFIG_DYNAMIC_RANGE_24_VAL ((0x3 << CONFIG_DYNAMIC_RANGE_OFST) & CONFIG_DYNAMIC_RANGE_MSK)
/* Control RW register */ // assumed for MY3
/* Control RW register */
#define CONTROL_REG (0x21 * REG_OFFSET + BASE_CONTROL)
#define CONTROL_STRT_ACQSTN_OFST (0)
#define CONTROL_STRT_ACQSTN_MSK (0x00000001 << CONTROL_STRT_ACQSTN_OFST)
#define CONTROL_STP_ACQSTN_OFST (1)
#define CONTROL_STP_ACQSTN_MSK (0x00000001 << CONTROL_STP_ACQSTN_OFST)
//#define CONTROL_RN_BSY_OFST (2) // assumed for MY3 TODO
//#define CONTROL_RN_BSY_MSK (0x00000001 << CONTROL_RN_BSY_OFST)
#define CONTROL_CRE_RST_OFST (10)
#define CONTROL_CRE_RST_MSK (0x00000001 << CONTROL_CRE_RST_OFST)
#define CONTROL_PRPHRL_RST_OFST (11) // Only GBE10?
@ -121,10 +118,24 @@
#define DTA_OFFSET_REG (0x24 * REG_OFFSET + BASE_CONTROL)
/* Pattern Control registers --------------------------------------------------*/
/* Pattern status Register*/
#define PAT_STATUS_REG (0x00 * REG_OFFSET + BASE_PATTERN_CONTROL)
#define PAT_STATUS_RUN_BUSY_OFST (0)
#define PAT_STATUS_RUN_BUSY_MSK (0x00000001 << PAT_STATUS_RUN_BUSY_OFST)
#define PAT_STATUS_WAIT_FOR_TRGGR_OFST (0)
#define PAT_STATUS_WAIT_FOR_TRGGR_MSK (0x00000001 << PAT_STATUS_WAIT_FOR_TRGGR_OFST)
#define PAT_STATUS_DLY_BFRE_TRGGR_OFST (0)
#define PAT_STATUS_DLY_BFRE_TRGGR_MSK (0x00000001 << PAT_STATUS_DLY_BFRE_TRGGR_OFST)
#define PAT_STATUS_FIFO_FULL_OFST (0)
#define PAT_STATUS_FIFO_FULL_MSK (0x00000001 << PAT_STATUS_FIFO_FULL_OFST)
#define PAT_STATUS_DLY_AFTR_TRGGR_OFST (0)
#define PAT_STATUS_DLY_AFTR_TRGGR_MSK (0x00000001 << PAT_STATUS_DLY_AFTR_TRGGR_OFST)
#define PAT_STATUS_CSM_BUSY_OFST (0)
#define PAT_STATUS_CSM_BUSY_MSK (0x00000001 << PAT_STATUS_CSM_BUSY_OFST)
/* Delay left 64bit Register */
#define GET_DELAY_LSB_REG (0x02 * REG_OFFSET + BASE_PATTERN_CONTROL)

View File

@ -17,10 +17,6 @@
#include <pthread.h>
#include <time.h>
#endif
// ------------------------------------------
#include <time.h>
// ------------------------------------------
// Global variable from slsDetectorServer_funcs
extern int debugflag;
@ -35,9 +31,6 @@ pthread_t pthread_virtual_tid;
int virtual_status = 0;
int virtual_stop = 0;
#endif
// ------------------------------------------
int temp_status = 0;
// ------------------------------------------
int32_t clkPhase[NUM_CLOCKS] = {0, 0, 0, 0, 0};
uint32_t clkFrequency[NUM_CLOCKS] = {0, 0, 0, 0, 0};
@ -45,6 +38,7 @@ uint32_t clkFrequency[NUM_CLOCKS] = {0, 0, 0, 0, 0};
int highvoltage = 0;
int dacValues[NDAC] = {0};
int detPos[2] = {0, 0};
uint32_t countermask = 0; // will be removed later when in firmware converted to mask
int isInitCheckDone() {
return initCheckDone;
@ -69,7 +63,7 @@ void basictests() {
}
return;
#else
FILE_LOG(logINFOBLUE, ("******** Mythen3 Server: do the checks *****************\n"));
FILE_LOG(logINFOBLUE, ("************ Mythen3 Server *********************\n"));
if (mapCSP0() == FAIL) {
strcpy(initErrorMessage,
"Could not map to memory. Dangerous to continue.\n");
@ -97,7 +91,7 @@ void basictests() {
if (fwversion >= MIN_REQRD_VRSN_T_RD_API)
sw_fw_apiversion = getFirmwareAPIVersion();
FILE_LOG(logINFOBLUE, ("************ Mythen3 Server *********************\n"
FILE_LOG(logINFOBLUE, ("*************************************************\n"
"Hardware Version:\t\t 0x%x\n"
"Detector IP Addr:\t\t 0x%x\n"
@ -371,8 +365,7 @@ void setupDetector() {
// dynamic range
setDynamicRange(DEFAULT_DYNAMIC_RANGE);
// enable all counters
bus_w(CONFIG_REG, bus_r(CONFIG_REG) & ~CONFIG_COUNTER_ENA_MSK);
bus_w(CONFIG_REG, bus_r(CONFIG_REG) | CONFIG_COUNTER_ENA_ALL_VAL);
setCounterMask(MAX_COUNTER_MSK);
// Initialization of acquistion parameters
@ -536,6 +529,66 @@ int64_t getPeriod() {
return get64BitReg(SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/ (1E-9 * FIXED_PLL_FREQUENCY);
}
void setCounterMask(uint32_t arg) {
if (arg == 0 || arg > MAX_COUNTER_MSK) {
return;
}
countermask = arg;
// convert mask into number of counters (until firmware converts to mask)
int ncounters = __builtin_popcount(countermask);
FILE_LOG(logINFO, ("Setting number of counters to %d\n", ncounters));
uint32_t val = 0;
switch (ncounters) {
case 1:
val = CONFIG_COUNTER_ENA_1_VAL;
break;
case 2:
val = CONFIG_COUNTER_ENA_2_VAL;
break;
default:
val = CONFIG_COUNTER_ENA_ALL_VAL;
break;
}
uint32_t addr = CONFIG_REG;
bus_w(addr, bus_r(addr) &~ CONFIG_COUNTER_ENA_MSK);
bus_w(addr, bus_r(addr) | val);
FILE_LOG(logDEBUG, ("Config Reg: 0x%x\n", bus_r(addr)));
}
uint32_t getCounterMask() {
uint32_t addr = CONFIG_REG;
uint32_t regval = (bus_r(addr) & CONFIG_COUNTER_ENA_MSK);
int ncounters = 0;
switch (regval) {
case CONFIG_COUNTER_ENA_1_VAL:
ncounters = 1;
break;
case CONFIG_COUNTER_ENA_2_VAL:
ncounters = 2;
break;
default:
ncounters = 3;
break;
}
// confirm ncounters work with mask saved in server (until firmware converts to mask)
int nc = __builtin_popcount(countermask);
// if not equal, make a mask of what is in register (will change once firmware changes)
if (nc != ncounters) {
switch (ncounters) {
case 1:
countermask = 0x1;
break;
case 2:
countermask = 0x3;
break;
default:
countermask = 0x7;
break;
}
}
return countermask;
}
int setDelayAfterTrigger(int64_t val) {
if (val < 0) {
FILE_LOG(logERROR, ("Invalid delay after trigger: %lld ns\n", (long long int)val));
@ -999,6 +1052,33 @@ void setPatternLoop(int level, int *startAddr, int *stopAddr, int *nLoop) {
}
}
int checkDetectorType() {
FILE_LOG(logINFO, ("Checking type of module\n"));
FILE* fd = fopen(TYPE_FILE_NAME, "r");
if (fd == NULL) {
FILE_LOG(logERROR, ("Could not open file %s to get type of the module attached\n", TYPE_FILE_NAME));
return -1;
}
char buffer[MAX_STR_LENGTH];
memset(buffer, 0, sizeof(buffer));
fread (buffer, MAX_STR_LENGTH, sizeof(char), fd);
if (strlen(buffer) == 0) {
FILE_LOG(logERROR, ("Could not read file %s to get type of the module attached\n", TYPE_FILE_NAME));
return -1;
}
int type = atoi(buffer);
if (type > TYPE_TOLERANCE) {
FILE_LOG(logERROR, ("No Module attached! Expected %d for Mythen, got %d\n", TYPE_MYTHEN3_MODULE_VAL, type));
return -2;
}
if (abs(type - TYPE_MYTHEN3_MODULE_VAL) > TYPE_TOLERANCE) {
FILE_LOG(logERROR, ("Wrong Module attached! Expected %d for Mythen, got %d\n", TYPE_MYTHEN3_MODULE_VAL, type));
return FAIL;
}
return OK;
}
int powerChip (int on){
if(on != -1){
if(on){
@ -1230,9 +1310,6 @@ int startStateMachine(){
FILE_LOG(logINFOBLUE, ("Starting State Machine\n"));
cleanFifos();
// ------------------------------------------
temp_status = 1;
// ------------------------------------------
//start state machine
bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STRT_ACQSTN_MSK);
@ -1311,45 +1388,53 @@ enum runStatus getRunStatus(){
}
#endif
FILE_LOG(logDEBUG1, ("Getting status\n"));
uint32_t retval = bus_r(PAT_STATUS_REG);
FILE_LOG(logINFO, ("Status Register: %08x\n",retval));
// ------------------------------------------
//uint32_t retval = bus_r(STATUS_REG);
//FILE_LOG(logINFO, ("Status Register: %08x\n",retval));
// running
if (temp_status) {
//if(retval & CONTROL_RN_BSY_MSK) {
// ------------------------------------------
FILE_LOG(logINFOBLUE, ("Status: Running\n"));
return RUNNING;
enum runStatus s;
//running
if (retval & PAT_STATUS_RUN_BUSY_MSK) {
if (retval & PAT_STATUS_WAIT_FOR_TRGGR_MSK) {
FILE_LOG(logINFOBLUE, ("Status: WAITING\n"));
s = WAITING;
} else {
if (retval & PAT_STATUS_DLY_BFRE_TRGGR_MSK) {
FILE_LOG(logINFO, ("Status: Delay before Trigger\n"));
} else if (retval & PAT_STATUS_DLY_AFTR_TRGGR_MSK) {
FILE_LOG(logINFO, ("Status: Delay after Trigger\n"));
}
FILE_LOG(logINFOBLUE, ("Status: RUNNING\n"));
s = RUNNING;
}
}
return IDLE;
//not running
else {
// stopped or error
if (retval & PAT_STATUS_FIFO_FULL_MSK) {
FILE_LOG(logINFOBLUE, ("Status: STOPPED\n")); //FIFO FULL??
s = STOPPED;
} else if (retval & PAT_STATUS_CSM_BUSY_MSK) {
FILE_LOG(logINFOBLUE, ("Status: READ MACHINE BUSY\n"));
s = TRANSMITTING;
} else if (!retval) {
FILE_LOG(logINFOBLUE, ("Status: IDLE\n"));
s = IDLE;
} else {
FILE_LOG(logERROR, ("Status: Unknown status %08x\n", retval));
s = ERROR;
}
}
return s;
}
void readFrame(int *ret, char *mess){
// wait for status to be done
// ------------------------------------------
//while(runBusy()){
// usleep(500);
//}
int64_t periodns = getPeriod();
int numFrames = getNumFrames();
int frameNr = 0;
// loop over number of frames
for(frameNr=0; frameNr!= numFrames; ++frameNr ) {
// sleep for exposure time
struct timespec begin, end;
clock_gettime(CLOCK_REALTIME, &begin);
usleep(periodns / 1000);
clock_gettime(CLOCK_REALTIME, &end);
}
usleep(1 * 1000 * 1000);
temp_status = 0;
// ------------------------------------------
while(runBusy()){
usleep(500);
}
#ifdef VIRTUAL
FILE_LOG(logINFOGREEN, ("acquisition successfully finished\n"));
@ -1372,13 +1457,9 @@ u_int32_t runBusy() {
#ifdef VIRTUAL
return virtual_status;
#endif
// ------------------------------------------
return temp_status;
//u_int32_t s = (bus_r(CONTROL_REG) & CONTROL_RN_BSY_OFST);
//FILE_LOG(logDEBUG1, ("Status Register: %08x\n", s));
//return s;
// ------------------------------------------
u_int32_t s = (bus_r(PAT_STATUS_REG) & PAT_STATUS_RUN_BUSY_MSK);
FILE_LOG(logDEBUG1, ("Status Register: %08x\n", s));
return s;
}
/* common */

View File

@ -7,14 +7,21 @@
#define CTRL_SRVR_INIT_TIME_US (300 * 1000)
/* Hardware Definitions */
#define NCHAN (128 * 3)
#define NCOUNTERS (3)
#define MAX_COUNTER_MSK (0x7)
#define NCHAN (128 * NCOUNTERS)
#define NCHIP (10)
#define NDAC (16)
#define HV_SOFT_MAX_VOLTAGE (200)
#define HV_HARD_MAX_VOLTAGE (530)
#define HV_DRIVER_FILE_NAME ("/etc/devlinks/hvdac")
#define DAC_DRIVER_FILE_NAME ("/etc/devlinks/dac")
#define DAC_DRIVER_FILE_NAME ("/etc/devlinks/dac")
#define TYPE_FILE_NAME ("/etc/devlinks/type")
#define DAC_MAX_MV (2048)
#define TYPE_MYTHEN3_MODULE_VAL (93)
#define TYPE_TOLERANCE (10)
#define TYPE_NO_MODULE_STARTING_VAL (800)
/** Default Parameters */
#define DEFAULT_DYNAMIC_RANGE (24)

View File

@ -98,7 +98,7 @@ u_int32_t writeRegister16(u_int32_t offset, u_int32_t data);
/**
* Get base address for memory copy
*/
uint64_t Blackfin_getBaseAddress();
uint32_t* Blackfin_getBaseAddress();
/**
* Map FPGA
*/

View File

@ -80,7 +80,7 @@ void allocateDetectorStructureMemory();
#endif
void setupDetector();
#if defined(CHIPTESTBOARDD) || defined(MOENCHD)
int allocateRAM();
int updateDatabytesandAllocateRAM();
void updateDataBytes();
#endif
@ -138,6 +138,8 @@ uint32_t getADCInvertRegister();
#if defined(CHIPTESTBOARDD) || defined(MOENCHD)
int setADCEnableMask(uint32_t mask);
uint32_t getADCEnableMask();
void setADCEnableMask_10G(uint32_t mask);
uint32_t getADCEnableMask_10G();
void setADCInvertRegister(uint32_t val);
uint32_t getADCInvertRegister();
int setExternalSamplingSource(int val);
@ -196,6 +198,10 @@ int getNumAnalogSamples();
int setNumDigitalSamples(int val);
int getNumDigitalSamples();
#endif
#ifdef MYTHEN3D
void setCounterMask(uint32_t arg);
uint32_t getCounterMask();
#endif
#if defined(JUNGFRAUD) || defined(GOTTHARDD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(MYTHEN3D)
int setDelayAfterTrigger(int64_t val);
@ -219,6 +225,7 @@ int64_t getMeasurementTime();
#endif
// parameters - module, settings
#if (!defined(CHIPTESTBOARDD)) && (!defined(MOENCHD)) && (!defined(MYTHEN3D)) && (!defined(GOTTHARD2D))
int setModule(sls_detector_module myMod, char* mess);
@ -305,12 +312,9 @@ void selectPrimaryInterface(int val);
int getPrimaryInterface();
void setupHeader(int iRxEntry, enum interfaceType type, uint32_t destip, uint64_t destmac, uint32_t destport, uint64_t sourcemac, uint32_t sourceip, uint32_t sourceport);
#endif
#if defined(JUNGFRAUD) || defined(GOTTHARD2D) || defined(MYTHEN3D)
#if defined(JUNGFRAUD) || defined(GOTTHARD2D) || defined(MYTHEN3D) || defined(CHIPTESTBOARDD) || defined(MOENCHD)
void calcChecksum(udp_header* udp);
#endif
#if defined(CHIPTESTBOARDD) || defined(MOENCHD)
long int calcChecksum(int sourceip, int destip);
#endif
#ifdef GOTTHARDD
int getAdcConfigured();
#endif
@ -425,6 +429,7 @@ uint64_t writePatternWord(int addr, uint64_t word);
int setPatternWaitAddress(int level, int addr);
uint64_t setPatternWaitTime(int level, uint64_t t);
void setPatternLoop(int level, int *startAddr, int *stopAddr, int *nLoop);
int checkDetectorType();
int powerChip (int on);
int setPhase(enum CLKINDEX ind, int val, int degrees);
int getPhase(enum CLKINDEX ind, int degrees);

View File

@ -201,4 +201,8 @@ int set_veto_photon(int);
int get_veto_photon(int);
int set_veto_refernce(int);
int get_burst_mode(int);
int set_burst_mode(int);
int set_burst_mode(int);
int set_adc_enable_mask_10g(int);
int get_adc_enable_mask_10g(int);
int set_counter_mask(int);
int get_counter_mask(int);

View File

@ -8,32 +8,32 @@
#include <sys/mman.h> // mmap
/* global variables */
u_int64_t CSP0BASE = 0;
u_int32_t* csp0base = 0;
#define CSP0 0x20200000
#define MEM_SIZE 0x100000
void bus_w16(u_int32_t offset, u_int16_t data) {
volatile u_int16_t *ptr1;
ptr1=(u_int16_t*)(CSP0BASE+offset*2);
ptr1=(u_int16_t*)(csp0base + offset / 2);
*ptr1=data;
}
u_int16_t bus_r16(u_int32_t offset){
volatile u_int16_t *ptr1;
ptr1=(u_int16_t*)(CSP0BASE+offset*2);
ptr1=(u_int16_t*)(csp0base + offset / 2);
return *ptr1;
}
void bus_w(u_int32_t offset, u_int32_t data) {
volatile u_int32_t *ptr1;
ptr1=(u_int32_t*)(CSP0BASE+offset*2);
ptr1=(u_int32_t*)(csp0base + offset / 2);
*ptr1=data;
}
u_int32_t bus_r(u_int32_t offset) {
volatile u_int32_t *ptr1;
ptr1=(u_int32_t*)(CSP0BASE+offset*2);
ptr1=(u_int32_t*)(csp0base + offset / 2);
return *ptr1;
}
@ -93,11 +93,11 @@ u_int32_t writeRegister16(u_int32_t offset, u_int32_t data) {
int mapCSP0(void) {
// if not mapped
if (CSP0BASE == 0) {
if (csp0base == 0) {
FILE_LOG(logINFO, ("Mapping memory\n"));
#ifdef VIRTUAL
CSP0BASE = malloc(MEM_SIZE);
if (CSP0BASE == NULL) {
csp0base = malloc(MEM_SIZE);
if (csp0base == NULL) {
FILE_LOG(logERROR, ("Could not allocate virtual memory.\n"));
return FAIL;
}
@ -110,15 +110,14 @@ int mapCSP0(void) {
return FAIL;
}
FILE_LOG(logDEBUG1, ("/dev/mem opened\n"));
CSP0BASE = mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0);
if (CSP0BASE == MAP_FAILED) {
csp0base = mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0);
if (csp0base == MAP_FAILED) {
FILE_LOG(logERROR, ("Can't map memmory area\n"));
return FAIL;
}
#endif
FILE_LOG(logINFO, ("CSPOBASE mapped from 0x%llx to 0x%llx\n",
(long long unsigned int)CSP0BASE,
(long long unsigned int)(CSP0BASE+MEM_SIZE)));
FILE_LOG(logINFO, ("csp0base mapped from %p to %p\n",
csp0base, (csp0base + MEM_SIZE)));
FILE_LOG(logINFO, ("Status Register: %08x\n", bus_r(STATUS_REG)));
}else
FILE_LOG(logINFO, ("Memory already mapped before\n"));
@ -126,6 +125,6 @@ int mapCSP0(void) {
}
uint64_t Blackfin_getBaseAddress() {
return CSP0BASE;
uint32_t* Blackfin_getBaseAddress() {
return csp0base;
}

View File

@ -303,6 +303,10 @@ const char* getFunctionName(enum detFuncs func) {
case F_SET_VETO_REFERENCE: return "F_SET_VETO_REFERENCE";
case F_GET_BURST_MODE: return "F_GET_BURST_MODE";
case F_SET_BURST_MODE: return "F_SET_BURST_MODE";
case F_SET_ADC_ENABLE_MASK_10G: return "F_SET_ADC_ENABLE_MASK_10G";
case F_GET_ADC_ENABLE_MASK_10G: return "F_GET_ADC_ENABLE_MASK_10G";
case F_SET_COUNTER_MASK: return "F_SET_COUNTER_MASK";
case F_GET_COUNTER_MASK: return "F_GET_COUNTER_MASK";
default: return "Unknown Function";
}
@ -483,6 +487,10 @@ void function_table() {
flist[F_SET_VETO_REFERENCE] = &set_veto_refernce;
flist[F_GET_BURST_MODE] = &get_burst_mode;
flist[F_SET_BURST_MODE] = &set_burst_mode;
flist[F_SET_ADC_ENABLE_MASK_10G] = &set_adc_enable_mask_10g;
flist[F_GET_ADC_ENABLE_MASK_10G] = &get_adc_enable_mask_10g;
flist[F_SET_COUNTER_MASK] = &set_counter_mask;
flist[F_GET_COUNTER_MASK] = &get_counter_mask;
// check
if (NUM_DET_FUNCTIONS >= RECEIVER_ENUM_START) {
@ -1739,6 +1747,22 @@ int start_acquisition(int file_des) {
FILE_LOG(logDEBUG1, ("Starting Acquisition\n"));
// only set
if (Server_VerifyLock() == OK) {
#if defined(CHIPTESTBOARDD) || defined(MOENCHD)
int mode = getReadoutMode();
int asamples = getNumAnalogSamples();
int dsamples = getNumDigitalSamples();
if ((mode == ANALOG_AND_DIGITAL || mode == ANALOG_ONLY) && (asamples <= 0)) {
ret = FAIL;
sprintf(mess, "Could not start acquisition. Invalid number of analog samples: %d.\n", asamples);
FILE_LOG(logERROR,(mess));
}
else if ((mode == ANALOG_AND_DIGITAL || mode == DIGITAL_ONLY) && (dsamples <= 0)) {
ret = FAIL;
sprintf(mess, "Could not start acquisition. Invalid number of digital samples: %d.\n", dsamples);
FILE_LOG(logERROR,(mess));
}
else
#endif
#ifdef EIGERD
// check for hardware mac and hardware ip
if (udpDetails.srcmac != getDetectorMAC()) {
@ -1857,6 +1881,22 @@ int start_and_read_all(int file_des) {
FILE_LOG(logDEBUG1, ("Starting Acquisition\n"));
// only set
if (Server_VerifyLock() == OK) {
#if defined(CHIPTESTBOARDD) || defined(MOENCHD)
int mode = getReadoutMode();
int asamples = getNumAnalogSamples();
int dsamples = getNumDigitalSamples();
if ((mode == ANALOG_AND_DIGITAL || mode == ANALOG_ONLY) && (asamples <= 0)) {
ret = FAIL;
sprintf(mess, "Could not start acquisition. Invalid number of analog samples: %d.\n", asamples);
FILE_LOG(logERROR,(mess));
}
else if ((mode == ANALOG_AND_DIGITAL || mode == DIGITAL_ONLY) && (dsamples <= 0)) {
ret = FAIL;
sprintf(mess, "Could not start acquisition. Invalid number of digital samples: %d.\n", dsamples);
FILE_LOG(logERROR,(mess));
}
else
#endif
#ifdef EIGERD
// check for hardware mac and hardware ip
if (udpDetails.srcmac != getDetectorMAC()) {
@ -2783,12 +2823,23 @@ int send_update(int file_des) {
sendData(file_des, &retval.xmin, sizeof(int), INT32);
sendData(file_des, &retval.xmax, sizeof(int), INT32);
#endif
// tengiga
#if defined(EIGERD) || defined(CHIPTESTBOARDD) || defined(MOENCHD)
i32 = enableTenGigabitEthernet(-1);
n = sendData(file_des,&i32,sizeof(i32),INT32);
if (n < 0) return printSocketReadError();
#endif
#if defined(CHIPTESTBOARDD) || defined(MOENCHD)
// adcmask
// 1g adcmask
i32 = getADCEnableMask();
n = sendData(file_des,&i32,sizeof(i32),INT32);
if (n < 0) return printSocketReadError();
// 10g adc mask
i32 = getADCEnableMask_10G();
n = sendData(file_des,&i32,sizeof(i32),INT32);
if (n < 0) return printSocketReadError();
#endif
// num udp interfaces
@ -2863,10 +2914,16 @@ int set_all_trimbits(int file_des) {
// set
if (arg >= 0 && Server_VerifyLock() == OK) {
ret = setAllTrimbits(arg);
//changes settings to undefined
setSettings(UNDEFINED);
FILE_LOG(logERROR, ("Settings has been changed to undefined (change all trimbits)\n"));
if (arg > 63) {
ret = FAIL;
strcpy(mess, "Cannot set all trimbits. Range: 0 - 63\n");
FILE_LOG(logERROR, (mess));
} else {
ret = setAllTrimbits(arg);
//changes settings to undefined
setSettings(UNDEFINED);
FILE_LOG(logERROR, ("Settings has been changed to undefined (change all trimbits)\n"));
}
}
// get
retval = getAllTrimbits();
@ -3784,8 +3841,29 @@ int power_chip(int file_des) {
#else
// set & get
if ((arg == -1) || (Server_VerifyLock() == OK)) {
retval = powerChip(arg);
FILE_LOG(logDEBUG1, ("Power chip: %d\n", retval));
#ifdef MYTHEN3D
// check only when powering on
if (arg != -1 && arg != 0) {
int type_ret = checkDetectorType();
if (type_ret == -1) {
ret = FAIL;
sprintf(mess, "Could not power on chip. Could not open file to get type of module attached.\n");
FILE_LOG(logERROR,(mess));
} else if (type_ret == -2) {
ret = FAIL;
sprintf(mess, "Could not power on chip. No module attached!\n");
FILE_LOG(logERROR,(mess));
} else if (type_ret == FAIL) {
ret = FAIL;
sprintf(mess, "Could not power on chip. Wrong module attached!\n");
FILE_LOG(logERROR,(mess));
}
}
#endif
if (ret == OK) {
retval = powerChip(arg);
FILE_LOG(logDEBUG1, ("Power chip: %d\n", retval));
}
validate(arg, retval, "power on/off chip", DEC);
#ifdef JUNGFRAUD
// narrow down error when powering on
@ -4231,7 +4309,7 @@ int set_adc_enable_mask(int file_des) {
if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0)
return printSocketReadError();
FILE_LOG(logDEBUG1, ("Seting ADC Enable Mask to %u\n", arg));
FILE_LOG(logDEBUG1, ("Seting 1Gb ADC Enable Mask to %u\n", arg));
#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD))
functionNotImplemented();
@ -4240,13 +4318,13 @@ int set_adc_enable_mask(int file_des) {
if (Server_VerifyLock() == OK) {
ret = setADCEnableMask(arg);
if (ret == FAIL) {
sprintf(mess, "Could not set ADC Enable mask to 0x%x. Could not allocate ram\n", arg);
sprintf(mess, "Could not set 1Gb ADC Enable mask to 0x%x.\n", arg);
FILE_LOG(logERROR,(mess));
} else {
uint32_t retval = getADCEnableMask();
if (arg != retval) {
ret = FAIL;
sprintf(mess, "Could not set ADC Enable mask. Set 0x%x, but read 0x%x\n", arg, retval);
sprintf(mess, "Could not set 1Gb ADC Enable mask. Set 0x%x, but read 0x%x\n", arg, retval);
FILE_LOG(logERROR,(mess));
}
}
@ -4261,14 +4339,58 @@ int get_adc_enable_mask(int file_des) {
memset(mess, 0, sizeof(mess));
uint32_t retval = -1;
FILE_LOG(logDEBUG1, ("Getting ADC Enable Mask \n"));
FILE_LOG(logDEBUG1, ("Getting 1Gb ADC Enable Mask \n"));
#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD))
functionNotImplemented();
#else
// get
retval = getADCEnableMask();
FILE_LOG(logDEBUG1, ("ADC Enable Mask retval: %u\n", retval));
FILE_LOG(logDEBUG1, ("1Gb ADC Enable Mask retval: %u\n", retval));
#endif
return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval));
}
int set_adc_enable_mask_10g(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
uint32_t arg = 0;
if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0)
return printSocketReadError();
FILE_LOG(logDEBUG1, ("Seting 10Gb ADC Enable Mask to %u\n", arg));
#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD))
functionNotImplemented();
#else
// only set
if (Server_VerifyLock() == OK) {
setADCEnableMask_10G(arg);
uint32_t retval = getADCEnableMask_10G();
if (arg != retval) {
ret = FAIL;
sprintf(mess, "Could not set 10Gb ADC Enable mask. Set 0x%x, but read 0x%x\n", arg, retval);
FILE_LOG(logERROR,(mess));
}
}
#endif
return Server_SendResult(file_des, INT32, UPDATE, NULL, 0);
}
int get_adc_enable_mask_10g(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
uint32_t retval = -1;
FILE_LOG(logDEBUG1, ("Getting 10Gb ADC Enable Mask\n"));
#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD))
functionNotImplemented();
#else
// get
retval = getADCEnableMask_10G();
FILE_LOG(logDEBUG1, ("10Gb ADC Enable Mask retval: %u\n", retval));
#endif
return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval));
}
@ -5481,7 +5603,7 @@ int set_readout_mode(int file_des) {
if (ret == OK) {
if (setReadoutMode(arg) == FAIL) {
ret = FAIL;
sprintf(mess, "Could not set allocate RAM to set readout mode\n");
sprintf(mess, "Could not set readout mode\n");
FILE_LOG(logERROR,(mess));
} else {
int retval = getReadoutMode();
@ -5618,7 +5740,7 @@ int get_clock_frequency(int file_des) {
#endif
default:
#if defined(GOTTHARD2D) || defined(MYTHEN3D)
if (c < NUM_CLOCKS) {
if (arg < NUM_CLOCKS) {
c = (enum CLKINDEX)arg;
break;
}
@ -6402,4 +6524,60 @@ int get_burst_mode(int file_des) {
FILE_LOG(logDEBUG1, ("Get burst mode:%d\n", retval));
#endif
return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval));
}
int set_counter_mask(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
uint32_t arg = 0;
if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0)
return printSocketReadError();
FILE_LOG(logINFO, ("Setting Counter mask:0x%x\n", arg));
#ifndef MYTHEN3D
functionNotImplemented();
#else
// only set
if (Server_VerifyLock() == OK) {
if (arg == 0) {
ret = FAIL;
sprintf(mess, "Could not set counter mask. Cannot set it to 0.\n");
FILE_LOG(logERROR, (mess));
} else if (arg > MAX_COUNTER_MSK) {
ret = FAIL;
sprintf(mess, "Could not set counter mask. Invalid counter bit enabled. Max number of counters: %d\n", NCOUNTERS);
FILE_LOG(logERROR, (mess));
} else {
setCounterMask(arg);
uint32_t retval = getCounterMask();
FILE_LOG(logDEBUG, ("counter mask retval: 0x%x\n", retval));
if (retval != arg) {
ret = FAIL;
sprintf(mess, "Could not set counter mask. Set 0x%x mask, got 0x%x mask\n", arg, retval);
FILE_LOG(logERROR, (mess));
}
}
}
#endif
return Server_SendResult(file_des, INT32, UPDATE, NULL, 0);
}
int get_counter_mask(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
uint32_t retval = -1;
FILE_LOG(logDEBUG1, ("Getting counter mask\n"));
#ifndef MYTHEN3D
functionNotImplemented();
#else
// get only
retval = getCounterMask();
FILE_LOG(logDEBUG, ("counter mask retval: 0x%x\n", retval));
#endif
return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval));
}

View File

@ -4,7 +4,7 @@ set(SOURCES
src/slsDetector.cpp
src/Detector.cpp
src/CmdProxy.cpp
src/CmdLineParser.cpp
src/CmdParser.cpp
)
set(HEADERS

View File

@ -406,7 +406,7 @@ class Detector {
Result<bool> getTenGiga(Positions pos = {}) const;
/** [Eiger][CTB] */
void setTenGiga(bool enable, Positions pos = {});
void setTenGiga(bool value, Positions pos = {});
/** [Eiger, Jungfrau] */
Result<bool> getTenGigaFlowControl(Positions pos = {}) const;
@ -525,7 +525,7 @@ class Detector {
Result<std::string> getFilePath(Positions pos = {}) const;
void setFilePath(const std::string &fname, Positions pos = {});
void setFilePath(const std::string &fpath, Positions pos = {});
Result<std::string> getFileNamePrefix(Positions pos = {}) const;
@ -755,7 +755,7 @@ class Detector {
/** [Eiger] Advanced
* used for pulsing chips */
void setPartialReset(bool enable, Positions pos = {});
void setPartialReset(bool value, Positions pos = {});
/** [Eiger] Advanced
* Pulse Pixel n times at x and y coordinates */
@ -910,7 +910,18 @@ class Detector {
void setBurstMode(bool enable, Positions pos = {});
/** [Gotthard2] */
Result<bool> getBurstMode(Positions pos = {});
Result<bool> getBurstMode(Positions pos = {});
/**************************************************
* *
* Mythen3 Specific *
* *
* ************************************************/
/** [Mythen3] */
Result<uint32_t> getCounterMask(Positions pos = {}) const;
/** [Mythen3] countermask bit set for each counter enabled */
void setCounterMask(uint32_t countermask, Positions pos = {});
/**************************************************
* *
@ -1015,6 +1026,12 @@ class Detector {
/** [CTB]*/
void setADCEnableMask(uint32_t mask, Positions pos = {});
/** [CTB]*/
Result<uint32_t> getTenGigaADCEnableMask(Positions pos = {}) const;
/** [CTB]*/
void setTenGigaADCEnableMask(uint32_t mask, Positions pos = {});
/** [CTB] */
Result<uint32_t> getADCInvert(Positions pos = {}) const;
@ -1037,7 +1054,7 @@ class Detector {
Result<std::vector<int>> getRxDbitList(Positions pos = {}) const;
/** [CTB] list contains the set of bits (0-63) to save */
void setRxDbitList(std::vector<int> list, Positions pos = {});
void setRxDbitList(const std::vector<int>& list, Positions pos = {});
/** [CTB] */
Result<int> getRxDbitOffset(Positions pos = {}) const;

View File

@ -1,5 +1,5 @@
#include <unistd.h>
#include <cstring>
#include <unistd.h>
#pragma once
/**
@short data structure to hold the detector data after postprocessing

View File

@ -1,5 +1,11 @@
#include "CmdLineParser.h"
/*
This file is used to generate the command line binaries
(sls_detector_get/put/acquire/help). By defines in CMake
we get the different files.
*/
#include "CmdParser.h"
#include "CmdProxy.h"
#include "Detector.h"
#include "sls_detector_defs.h"
@ -35,7 +41,7 @@ int main(int argc, char *argv[]) {
}
}
sls::CmdLineParser parser;
sls::CmdParser parser;
parser.Parse(argc, argv);
// If we called sls_detector_acquire, add the acquire command
@ -57,16 +63,11 @@ int main(int argc, char *argv[]) {
}
try {
//How big should this try block be?
// How big should this try block be?
sls::Detector det(parser.multi_id());
sls::CmdProxy proxy(&det);
auto cmd = proxy.Call(parser.command(), parser.arguments(),
parser.detector_id(), action);
// TODO! move this check into CmdProxy
if (!cmd.empty()) {
std::cout << cmd
<< " Unknown command, use list to list all commands\n";
}
proxy.Call(parser.command(), parser.arguments(), parser.detector_id(),
action);
} catch (const sls::RuntimeError &e) {
// OK to catch and do nothing since this will print the error message
// and command line app will anyway exit

View File

@ -1,5 +1,5 @@
#include "CmdLineParser.h"
#include "CmdParser.h"
#include "sls_detector_defs.h"
#include <cstdio>
#include <cstring>
@ -9,8 +9,8 @@
namespace sls {
void CmdLineParser::Print() {
std::cout << "\nCmdLineParser::Print()\n";
void CmdParser::Print() {
std::cout << "\nCmdParser::Print()\n";
std::cout << "\tmulti_id: " << multi_id_
<< ", detector_id: " << detector_id_ << std::endl;
std::cout << "\texecutable: " << executable_ << '\n';
@ -23,7 +23,7 @@ void CmdLineParser::Print() {
std::cout << "\n\n";
};
void CmdLineParser::Parse(int argc, const char *const argv[]) {
void CmdParser::Parse(int argc, const char *const argv[]) {
Reset();
executable_ = argv[0]; // first arg is calling binary
if (argc > 1) {
@ -36,7 +36,7 @@ void CmdLineParser::Parse(int argc, const char *const argv[]) {
}
}
void CmdLineParser::Parse(const std::string &s) {
void CmdParser::Parse(const std::string &s) {
Reset();
std::istringstream iss(s);
auto it = std::istream_iterator<std::string>(iss);
@ -59,7 +59,7 @@ void CmdLineParser::Parse(const std::string &s) {
DecodeIdAndPosition(command_.c_str());
}
void CmdLineParser::DecodeIdAndPosition(const char *c) {
void CmdParser::DecodeIdAndPosition(const char *c) {
bool contains_id = std::strchr(c, '-') != nullptr;
bool contains_pos = std::strchr(c, ':') != nullptr;
char tmp[100];
@ -91,9 +91,9 @@ void CmdLineParser::DecodeIdAndPosition(const char *c) {
}
}
std::vector<const char *> CmdLineParser::argv() const {
std::vector<const char *> CmdParser::argv() const {
std::vector<const char *> vec;
if (command_.empty() != true) {
if (!command_.empty()) {
vec.push_back(&command_.front());
}
for (auto &arg : arguments_) {
@ -103,7 +103,7 @@ std::vector<const char *> CmdLineParser::argv() const {
}
std::string CmdLineParser::cli_line() const{
std::string CmdParser::cli_line() const{
std::ostringstream os;
os << command_;
for (const auto & arg : arguments_)
@ -111,7 +111,7 @@ std::string CmdLineParser::cli_line() const{
return os.str();
}
void CmdLineParser::Reset(){
void CmdParser::Reset(){
multi_id_ = 0;
detector_id_ = -1;
help_ = false;

View File

@ -19,7 +19,7 @@ reason that the header file is not exposed.
namespace sls {
class CmdLineParser {
class CmdParser {
public:
void Parse(int argc, const char *const argv[]);
void Parse(const std::string &s);

View File

@ -25,9 +25,9 @@ std::ostream &operator<<(std::ostream &os,
return os;
}
std::string CmdProxy::Call(const std::string &command,
const std::vector<std::string> &arguments,
int detector_id, int action, std::ostream &os) {
void CmdProxy::Call(const std::string &command,
const std::vector<std::string> &arguments, int detector_id,
int action, std::ostream &os) {
cmd = command;
args = arguments;
det_id = detector_id;
@ -37,9 +37,9 @@ std::string CmdProxy::Call(const std::string &command,
auto it = functions.find(cmd);
if (it != functions.end()) {
os << ((*this).*(it->second))(action);
return {};
} else {
return cmd;
throw sls::RuntimeError(
cmd + " Unknown command, use list to list all commands");
}
}
@ -56,7 +56,6 @@ bool CmdProxy::ReplaceIfDepreciated(std::string &command) {
return false;
}
std::vector<std::string> CmdProxy::GetProxyCommands() {
std::vector<std::string> commands;
for (const auto &it : functions)
@ -82,7 +81,7 @@ std::string CmdProxy::ListCommands(int action) {
return "list\n\tlists all available commands, list deprecated - "
"list deprecated commands\n";
if (args.size() == 0) {
if (args.empty()) {
auto commands = GetProxyCommands();
std::cout << "These " << commands.size() << " commands are available\n";
for (auto &c : commands)
@ -92,7 +91,7 @@ std::string CmdProxy::ListCommands(int action) {
if (args[0] == "deprecated") {
std::cout << "The following " << depreciated_functions.size()
<< " commands are deprecated\n";
size_t field_width = 20;
const size_t field_width = 20;
for (const auto &it : depreciated_functions) {
std::cout << std::right << std::setw(field_width) << it.first
<< " -> " << it.second << '\n';
@ -125,13 +124,13 @@ std::string CmdProxy::Hostname(int action) {
"all modules concatenated by +."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getHostname({det_id});
os << OutString(t) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.size() < 1) {
if (args.empty()) {
WrongNumberOfParameters(1);
}
if (det_id != -1) {
@ -216,7 +215,7 @@ std::string CmdProxy::FirmwareVersion(int action) {
"for Eiger."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getFirmwareVersion({det_id});
@ -239,7 +238,7 @@ std::string CmdProxy::Versions(int action) {
if (action == defs::HELP_ACTION) {
os << "\n\tPrint all versions and detector type" << '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getFirmwareVersion();
@ -272,7 +271,7 @@ std::string CmdProxy::PackageVersion(int action) {
if (action == defs::HELP_ACTION) {
os << "\n\tPackage version (git branch)." << '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
os << det->getPackageVersion() << '\n';
@ -290,7 +289,7 @@ std::string CmdProxy::ClientVersion(int action) {
if (action == defs::HELP_ACTION) {
os << "\n\tClient software version in format [0xYYMMDD]." << '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
os << ToStringHex(det->getClientVersion()) << '\n';
@ -312,7 +311,7 @@ std::string CmdProxy::DetectorSize(int action) {
"packet header."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getDetectorSize();
@ -355,7 +354,7 @@ std::string CmdProxy::Speed(int action) {
// after change
}
if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getSpeed({det_id});
@ -406,7 +405,7 @@ std::string CmdProxy::Adcphase(int action) {
<< '\n';
} else if (action == defs::GET_ACTION) {
Result<int> t;
if (args.size() == 0) {
if (args.empty()) {
t = det->getADCPhase({det_id});
os << OutString(t) << '\n';
} else if (args.size() == 1) {
@ -657,7 +656,7 @@ std::string CmdProxy::DacValues(int action) {
size_t spacepos = names[i].find(' ');
// chip test board (dac)
if (spacepos != std::string::npos) {
if (args.size() == 0) {
if (args.empty()) {
args.resize(1);
}
args[0] = names[i].substr(spacepos + 1 - 1);
@ -704,8 +703,8 @@ std::vector<std::string> CmdProxy::DacCommands() {
case defs::MYTHEN3:
return std::vector<std::string>{
"vcassh", "vth2", "vshaper", "vshaperneg", "vipre_out", "vth3",
"vth1", "vicin", "vcas", "vpreamp", "vph", "vipre",
"viinsh", "vpl", "vtrim", "vdcsh"};
"vth1", "vicin", "vcas", "vpreamp", "vpl", "vipre",
"viinsh", "vph", "vtrim", "vdcsh"};
break;
case defs::CHIPTESTBOARD:
return std::vector<std::string>{
@ -733,7 +732,7 @@ std::string CmdProxy::DynamicRange(int action) {
"pixel in detector."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getDynamicRange({det_id});
@ -764,7 +763,7 @@ std::string CmdProxy::Threshold(int action) {
"eV"
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getThresholdEnergy({det_id});
@ -828,7 +827,7 @@ std::string CmdProxy::GapPixels(int action) {
"back. 4 bit mode gap pixels only ind ata call back."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getRxAddGapPixels({det_id});
@ -859,13 +858,13 @@ std::string CmdProxy::TrimEnergies(int action) {
"corresponding trim folders."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getTrimEnergies({det_id});
os << OutString(t) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.size() < 1) {
if (args.empty()) {
WrongNumberOfParameters(1);
}
unsigned int ntrim = args.size();
@ -890,7 +889,7 @@ std::string CmdProxy::RateCorrection(int action) {
"correction."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getRateCorrection({det_id});
@ -924,7 +923,7 @@ std::string CmdProxy::Activate(int action) {
"pad data files for deactivates readouts."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getActive({det_id});
@ -935,7 +934,7 @@ std::string CmdProxy::Activate(int action) {
}
os << OutString(t) << ' ' << OutString(pResult) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.size() < 1 || args.size() > 2) {
if (args.empty() || args.size() > 2) {
WrongNumberOfParameters(2);
}
int t = std::stoi(args[0]);
@ -1039,7 +1038,7 @@ std::string CmdProxy::Quad(int action) {
"(Specific hardware required)."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getQuad({det_id});
@ -1074,7 +1073,7 @@ std::string CmdProxy::TemperatureEvent(int action) {
"temperature and temperature event has to be cleared."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getTemperatureEvent({det_id});
@ -1106,7 +1105,7 @@ std::string CmdProxy::ROI(int action) {
"Default is all channels enabled (-1 -1). "
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getROI({det_id});
@ -1141,7 +1140,7 @@ std::string CmdProxy::ClearROI(int action) {
} else if (action == defs::GET_ACTION) {
throw sls::RuntimeError("Cannot get");
} else if (action == defs::PUT_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
det->clearROI({det_id});
@ -1152,69 +1151,125 @@ std::string CmdProxy::ClearROI(int action) {
return os.str();
}
/* Gotthard2 Specific */
std::string CmdProxy::InjectChannel(int action) {
std::ostringstream os;
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "[offset] [increment]\n\t[Gotthard2] Inject channels with current source for calibration. Offset is starting channel that is injected, increment determines succeeding channels to be injected." << '\n';
os << "[offset] [increment]\n\t[Gotthard2] Inject channels with "
"current source for calibration. Offset is starting channel that "
"is injected, increment determines succeeding channels to be "
"injected."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
WrongNumberOfParameters(0);
}
auto t = det->getInjectChannel({det_id});
os << OutString(t) << '\n';
} else if (action == defs::PUT_ACTION) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getInjectChannel({det_id});
os << OutString(t) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.size() != 2) {
WrongNumberOfParameters(2);
}
det->setInjectChannel(std::stoi(args[0]), std::stoi(args[1]), {det_id});
WrongNumberOfParameters(2);
}
det->setInjectChannel(std::stoi(args[0]), std::stoi(args[1]), {det_id});
os << sls::ToString(args) << '\n';
} else {
} else {
throw sls::RuntimeError("Unknown action");
}
return os.str();
}
std::string CmdProxy::VetoPhoton(int action) {
std::ostringstream os;
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "[n_chip] [#photons] [energy in keV] [reference file]\n\t[Gotthard2] Set veto reference for 128 channels for chip n_chip according to referenc file and #photons and energy in keV." << '\n';
os << "[n_chip] [#photons] [energy in keV] [reference "
"file]\n\t[Gotthard2] Set veto reference for 128 channels for "
"chip n_chip according to referenc file and #photons and energy "
"in keV."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 1) {
WrongNumberOfParameters(1);
}
auto t = det->getVetoPhoton(std::stoi(args[0]), {det_id});
os << args[0] << ' ' << OutStringHex(t) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.size() != 1) {
WrongNumberOfParameters(1);
}
auto t = det->getVetoPhoton(std::stoi(args[0]), {det_id});
os << args[0] << ' ' << OutStringHex(t) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.size() != 4) {
WrongNumberOfParameters(4);
}
det->setVetoPhoton(std::stoi(args[0]), std::stoi(args[1]), std::stoi(args[2]), args[3], {det_id});
WrongNumberOfParameters(4);
}
det->setVetoPhoton(std::stoi(args[0]), std::stoi(args[1]),
std::stoi(args[2]), args[3], {det_id});
os << sls::ToString(args) << '\n';
} else {
} else {
throw sls::RuntimeError("Unknown action");
}
return os.str();
}
std::string CmdProxy::VetoReference(int action) {
std::ostringstream os;
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "[gain index] [12 bit value in hex] \n\t[Gotthard2] Set veto reference for all 128 channels for all chips." << '\n';
os << "[gain index] [12 bit value in hex] \n\t[Gotthard2] Set veto "
"reference for all 128 channels for all chips."
<< '\n';
} else if (action == defs::GET_ACTION) {
throw sls::RuntimeError("cannot get vetoref. Did you mean vetophoton?");
} else if (action == defs::PUT_ACTION) {
} else if (action == defs::PUT_ACTION) {
if (args.size() != 2) {
WrongNumberOfParameters(2);
}
det->setVetoReference(std::stoi(args[0]), stoiHex(args[1]), {det_id});
WrongNumberOfParameters(2);
}
det->setVetoReference(std::stoi(args[0]), stoiHex(args[1]), {det_id});
os << sls::ToString(args) << '\n';
} else {
} else {
throw sls::RuntimeError("Unknown action");
}
return os.str();
}
/* Mythen3 Specific */
std::string CmdProxy::Counters(int action) {
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "[i0] [i1] [i2]... \n\t[Mythen3] List of counters enabled. Each "
"element in list can be 0 - 2 and must be non repetitive."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto mask = det->getCounterMask({det_id}).squash(-1);
// scan counter enable mask to get vector
std::vector <int> result;
for (size_t i = 0; i < 32; ++i) {
if (mask & (1 << i)) {
result.push_back((int)i);
}
}
os << sls::ToString(result) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.empty()) {
WrongNumberOfParameters(1);
}
// convert vector to counter enable mask
uint32_t mask = 0;
for (size_t i = 0; i < args.size(); ++i) {
int val = std::stoi(args[i]);
// already enabled earlier
if (mask & (1 << val)) {
std::ostringstream oss;
oss << "Duplicate counter values (" << val << ") in arguments";
throw sls::RuntimeError(oss.str());
}
mask |= (1 << val);
}
det->setCounterMask(mask, {det_id});
os << sls::ToString(args) << '\n';
} else {
throw sls::RuntimeError("Unknown action");
}
return os.str();
@ -1230,7 +1285,7 @@ std::string CmdProxy::Samples(int action) {
"digitial) expected."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto a = det->getNumberOfAnalogSamples({det_id});
@ -1266,7 +1321,7 @@ std::string CmdProxy::Dbitphase(int action) {
<< '\n';
} else if (action == defs::GET_ACTION) {
Result<int> t;
if (args.size() == 0) {
if (args.empty()) {
t = det->getDBITPhase({det_id});
os << OutString(t) << '\n';
} else if (args.size() == 1) {
@ -1336,17 +1391,18 @@ std::string CmdProxy::ReceiverDbitList(int action) {
if (action == defs::HELP_ACTION) {
os << "[all] or [i0] [i1] [i2]... \n\t[Ctb] List of digital signal "
"bits read out. If all is used instead of a list, all digital "
"bits (64) enabled. Each element in list can be 0 - 63 and non "
"bits (64) enabled. Each element in list can be 0 - 63 and must "
"be non "
"repetitive."
<< '\n';
} else if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getRxDbitList({det_id});
os << OutString(t) << '\n';
} else if (action == defs::PUT_ACTION) {
if (args.size() < 1) {
if (args.empty()) {
WrongNumberOfParameters(1);
}
std::vector<int> t;
@ -1476,7 +1532,7 @@ std::string CmdProxy::PatternLoopAddresses(int action) {
"Unknown command, use list to list all commands");
}
if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getPatternLoopAddresses(level, {det_id});
@ -1522,7 +1578,7 @@ std::string CmdProxy::PatternLoopCycles(int action) {
"Unknown command, use list to list all commands");
}
if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getPatternLoopCycles(level, {det_id});
@ -1567,7 +1623,7 @@ std::string CmdProxy::PatternWaitAddress(int action) {
"Unknown command, use list to list all commands");
}
if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getPatternWaitAddr(level, {det_id});
@ -1612,7 +1668,7 @@ std::string CmdProxy::PatternWaitTime(int action) {
"Unknown command, use list to list all commands");
}
if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getPatternWaitTime(level, {det_id});
@ -1685,7 +1741,7 @@ std::string CmdProxy::MinMaxEnergyThreshold(int action) {
"Unknown command, use list to list all commands");
}
if (action == defs::GET_ACTION) {
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getDetectorMinMaxEnergyThreshold(emax, {det_id});
@ -1913,7 +1969,7 @@ std::string CmdProxy::UserDetails(int action) {
if (det_id != -1) {
throw sls::RuntimeError("Cannot execute this at module level");
}
if (args.size() != 0) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getUserDetails();

View File

@ -2,8 +2,8 @@
#include "Detector.h"
#include "Result.h"
#include "sls_detector_exceptions.h"
#include "network_utils.h"
#include "sls_detector_exceptions.h"
#include <iostream>
#include <map>
#include <string>
@ -416,7 +416,7 @@ class CmdProxy {
public:
explicit CmdProxy(Detector *ptr) : det(ptr) {}
std::string Call(const std::string &command,
void Call(const std::string &command,
const std::vector<std::string> &arguments, int detector_id = -1,
int action = -1, std::ostream &os = std::cout);
@ -449,7 +449,7 @@ class CmdProxy {
}
inline unsigned int stoiHex(const std::string& s) {
unsigned long lresult = stoul(s, 0, 16);
unsigned long lresult = stoul(s, nullptr, 16);
unsigned int result = lresult;
if (result != lresult) {
throw std::out_of_range("cannot convert to unsigned int");
@ -458,7 +458,7 @@ class CmdProxy {
}
inline unsigned long int stoulHex(const std::string& s) {
unsigned long result = stoul(s, 0, 16);
unsigned long result = stoul(s, nullptr, 16);
return result;
}
@ -497,6 +497,8 @@ class CmdProxy {
{"rx_udpmac2", "udp_dstmac2"},
{"rx_udpport", "udp_dstport"},
{"rx_udpport2", "udp_dstport2"},
{"flowcontrol_10g", "flowcontrol10g"},
/* Receiver Config */
{"r_silent", "rx_silent"},
@ -527,6 +529,7 @@ class CmdProxy {
{"digitest", "imagetest"},
/* Gotthard2 Specific */
/* Mythen3 Specific */
/* CTB Specific */
{"flags", "romode"},
{"i_a", "im_a"},
@ -549,7 +552,7 @@ class CmdProxy {
/* configuration */
{"config", &CmdProxy::config},
{"free2", &CmdProxy::free},
{"free", &CmdProxy::free},
{"parameters", &CmdProxy::parameters},
{"hostname", &CmdProxy::Hostname},
{"virtual", &CmdProxy::VirtualServer},
@ -698,7 +701,7 @@ class CmdProxy {
{"udp_dstport2", &CmdProxy::udp_dstport2},
{"rx_printconfig", &CmdProxy::rx_printconfig},
{"tengiga", &CmdProxy::tengiga},
{"flowcontrol_10g", &CmdProxy::flowcontrol_10g},
{"flowcontrol10g", &CmdProxy::flowcontrol10g},
{"txndelay_frame", &CmdProxy::txndelay_frame},
{"txndelay_left", &CmdProxy::txndelay_left},
{"txndelay_right", &CmdProxy::txndelay_right},
@ -783,6 +786,9 @@ class CmdProxy {
{"vetoref", &CmdProxy::VetoReference},
{"burstmode", &CmdProxy::burstmode},
/* Mythen3 Specific */
{"counters", &CmdProxy::Counters},
/* CTB Specific */
{"samples", &CmdProxy::Samples},
{"asamples", &CmdProxy::asamples},
@ -815,6 +821,7 @@ class CmdProxy {
{"im_io", &CmdProxy::im_io},
{"adc", &CmdProxy::SlowAdc},
{"adcenable", &CmdProxy::adcenable},
{"adcenable10g", &CmdProxy::adcenable10g},
{"adcinvert", &CmdProxy::adcinvert},
{"extsampling", &CmdProxy::extsampling},
{"extsamplingsrc", &CmdProxy::extsamplingsrc},
@ -935,7 +942,9 @@ class CmdProxy {
/* Gotthard2 Specific */
std::string InjectChannel(int action);
std::string VetoPhoton(int action);
std::string VetoReference(int action);
std::string VetoReference(int action);
/* Mythen3 Specific */
std::string Counters(int action);
/* CTB Specific */
std::string Samples(int action);
std::string Dbitphase(int action);
@ -1343,7 +1352,7 @@ class CmdProxy {
INTEGER_COMMAND(tengiga, getTenGiga, setTenGiga, std::stoi,
"[0, 1]\n\t[Eiger][Ctb] 10GbE Enable.");
INTEGER_COMMAND(flowcontrol_10g, getTenGigaFlowControl, setTenGigaFlowControl, std::stoi,
INTEGER_COMMAND(flowcontrol10g, getTenGigaFlowControl, setTenGigaFlowControl, std::stoi,
"[0, 1]\n\t[Eiger][Jungfrau] 10GbE Flow Control.");
INTEGER_COMMAND(txndelay_frame, getTransmissionDelayFrame, setTransmissionDelayFrame, std::stoi,
@ -1523,6 +1532,8 @@ class CmdProxy {
INTEGER_COMMAND(burstmode, getBurstMode, setBurstMode, std::stoi,
"[0, 1]\n\t[Gotthard2] 1 sets to burst mode. 0 sets to continuous mode. Default is burst mode.");
/* Mythen3 Specific */
/* CTB Specific */
INTEGER_COMMAND(asamples, getNumberOfAnalogSamples, setNumberOfAnalogSamples, std::stoi,
@ -1607,7 +1618,10 @@ class CmdProxy {
"\n\t[Ctb] Measured current of power supply io in mA.");
INTEGER_COMMAND_HEX(adcenable, getADCEnableMask, setADCEnableMask, stoiHex,
"[bitmask]\n\t[Ctb] ADC Enable Mask.");
"[bitmask]\n\t[Ctb] ADC Enable Mask for 1Gb Mode for each 32 ADC channel.");
INTEGER_COMMAND_HEX(adcenable10g, getTenGigaADCEnableMask, setTenGigaADCEnableMask, stoiHex,
"[bitmask]\n\t[Ctb] ADC Enable Mask for 10Gb mode for each 32 ADC channel. However, if any of consecutive 4 bits are enabled, the complete 4 bits are enabled.");
INTEGER_COMMAND_HEX(adcinvert, getADCInvert, setADCInvert, stoiHex,
"[bitmask]\n\t[Ctb][Jungfrau] ADC Inversion Mask.\n\t[Jungfrau] Inversions on top of the default mask.");
@ -1630,16 +1644,16 @@ class CmdProxy {
EXECUTE_SET_COMMAND_NOID_1ARG(savepattern, savePattern,
"[fname]\n\t[Ctb] Saves pattern to file (ascii). Also executes pattern.");
INTEGER_COMMAND_HEX(patioctrl, getPatternIOControl, setPatternIOControl, std::stoull,
INTEGER_COMMAND_HEX(patioctrl, getPatternIOControl, setPatternIOControl, stoulHex,
"[64 bit mask]\n\t[Ctb] 64 bit mask defining input (0) and output (1) signals.");
INTEGER_COMMAND_HEX(patclkctrl, getPatternClockControl, setPatternClockControl, std::stoull,
INTEGER_COMMAND_HEX(patclkctrl, getPatternClockControl, setPatternClockControl, stoulHex,
"[64 bit mask]\n\t[Ctb] 64 bit mask defining output clock enable.");
INTEGER_COMMAND_HEX(patmask, getPatternMask, setPatternMask, std::stoull,
INTEGER_COMMAND_HEX(patmask, getPatternMask, setPatternMask, stoulHex,
"[64 bit mask]\n\t[Ctb] 64 bit mask applied to every pattern. Only these bits for each pattern will be masked against.");
INTEGER_COMMAND_HEX(patsetbit, getPatternBitMask, setPatternBitMask, std::stoull,
INTEGER_COMMAND_HEX(patsetbit, getPatternBitMask, setPatternBitMask, stoulHex,
"[64 bit mask]\n\t[Ctb] 64 bit values applied to the selected patmask for every pattern.");
/* Moench */

View File

@ -1,5 +1,5 @@
#include "Detector.h"
#include "CmdLineParser.h"
#include "CmdParser.h"
#include "CmdProxy.h"
#include "container_utils.h"
#include "detectorData.h"
@ -58,7 +58,7 @@ void Detector::loadConfig(const std::string &fname) {
void Detector::loadParameters(const std::string &fname) {
CmdProxy proxy(this);
CmdLineParser parser;
CmdParser parser;
std::ifstream input_file;
input_file.open(fname.c_str(), std::ios_base::in);
if (!input_file.is_open()) {
@ -86,8 +86,8 @@ Result<std::string> Detector::getHostname(Positions pos) const {
return pimpl->Parallel(&slsDetector::getHostname, pos);
}
void Detector::setHostname(const std::vector<std::string> &value) {
pimpl->setHostname(value);
void Detector::setHostname(const std::vector<std::string> &hostname) {
pimpl->setHostname(hostname);
}
void Detector::setVirtualDetectorServers(int numServers, int startingPort) {
@ -760,9 +760,9 @@ Result<bool> Detector::getRxZmqDataStream(Positions pos) const {
-1);
}
void Detector::setRxZmqDataStream(bool enable, Positions pos) {
void Detector::setRxZmqDataStream(bool value, Positions pos) {
pimpl->Parallel(&slsDetector::enableDataStreamingFromReceiver, pos,
static_cast<int>(enable));
static_cast<int>(value));
}
Result<int> Detector::getRxZmqFrequency(Positions pos) const {
@ -887,8 +887,8 @@ void Detector::setSettingsPath(const std::string &value, Positions pos) {
pimpl->Parallel(&slsDetector::setSettingsDir, pos, value);
}
void Detector::loadTrimbits(const std::string &value, Positions pos) {
pimpl->Parallel(&slsDetector::loadSettingsFile, pos, value);
void Detector::loadTrimbits(const std::string &fname, Positions pos) {
pimpl->Parallel(&slsDetector::loadSettingsFile, pos, fname);
}
Result<bool> Detector::getRxAddGapPixels(Positions pos) const {
@ -1030,12 +1030,12 @@ Result<bool> Detector::getQuad(Positions pos) const {
return pimpl->Parallel(&slsDetector::getQuad, pos);
}
void Detector::setQuad(const bool value) {
if (value && size() > 1) {
void Detector::setQuad(const bool enable) {
if (enable && size() > 1) {
throw RuntimeError("Cannot set Quad type as it is available only for 1 "
"Eiger Quad Half module.");
}
pimpl->Parallel(&slsDetector::setQuad, {}, value);
pimpl->Parallel(&slsDetector::setQuad, {}, enable);
}
// Jungfrau Specific
@ -1188,6 +1188,16 @@ Result<bool> Detector::getBurstMode(Positions pos) {
return pimpl->Parallel(&slsDetector::getBurstMode, pos);
}
// Mythen3 Specific
Result<uint32_t> Detector::getCounterMask(Positions pos) const {
return pimpl->Parallel(&slsDetector::getCounterMask, pos);
}
void Detector::setCounterMask(uint32_t countermask, Positions pos) {
pimpl->Parallel(&slsDetector::setCounterMask, pos, countermask);
}
// CTB Specific
Result<int> Detector::getNumberOfAnalogSamples(Positions pos) const {
@ -1368,6 +1378,14 @@ void Detector::setADCEnableMask(uint32_t mask, Positions pos) {
pimpl->Parallel(&slsDetector::setADCEnableMask, pos, mask);
}
Result<uint32_t> Detector::getTenGigaADCEnableMask(Positions pos) const {
return pimpl->Parallel(&slsDetector::getTenGigaADCEnableMask, pos);
}
void Detector::setTenGigaADCEnableMask(uint32_t mask, Positions pos) {
pimpl->Parallel(&slsDetector::setTenGigaADCEnableMask, pos, mask);
}
Result<uint32_t> Detector::getADCInvert(Positions pos) const {
return pimpl->Parallel(&slsDetector::getADCInvert, pos);
}
@ -1396,7 +1414,7 @@ Result<std::vector<int>> Detector::getRxDbitList(Positions pos) const {
return pimpl->Parallel(&slsDetector::getReceiverDbitList, pos);
}
void Detector::setRxDbitList(std::vector<int> list, Positions pos) {
void Detector::setRxDbitList(const std::vector<int>& list, Positions pos) {
pimpl->Parallel(&slsDetector::setReceiverDbitList, pos, list);
}
@ -1758,6 +1776,7 @@ std::vector<int> Detector::getPortNumbers(int start_port) {
break;
}
std::vector<int> res;
res.reserve(size());
for (int idet = 0; idet < size(); ++idet) {
res.push_back(start_port + (idet * num_sockets_per_detector));
}

View File

@ -8,10 +8,10 @@
#include "sls_detector_exceptions.h"
#include "versionAPI.h"
#include "ToString.h"
#include "container_utils.h"
#include "network_utils.h"
#include "string_utils.h"
#include "ToString.h"
#include <cstring>
#include <iomanip>
@ -643,7 +643,7 @@ void multiSlsDetector::readFrameFromReceiver() {
<< "\n\tsingledetrowoffset: " << singledetrowoffset
<< "\n\trowoffset: " << rowoffset;
if (eiger && (flippedDataX != 0u)) {
if (eiger && (flippedDataX != 0U)) {
for (uint32_t i = 0; i < nPixelsY; ++i) {
memcpy(((char *)multiframe) +
((yoffset + (nPixelsY - 1 - i)) *
@ -1008,82 +1008,90 @@ int multiSlsDetector::acquire() {
return FAIL;
}
struct timespec begin, end;
clock_gettime(CLOCK_REALTIME, &begin);
try {
struct timespec begin, end;
clock_gettime(CLOCK_REALTIME, &begin);
// in the real time acquisition loop, processing thread will wait for a post
// each time
sem_init(&sem_newRTAcquisition, 1, 0);
// in the real time acquistion loop, main thread will wait for processing
// thread to be done each time (which in turn waits for receiver/ext
// process)
sem_init(&sem_endRTAcquisition, 1, 0);
// in the real time acquisition loop, processing thread will wait for a post
// each time
sem_init(&sem_newRTAcquisition, 1, 0);
// in the real time acquistion loop, main thread will wait for processing
// thread to be done each time (which in turn waits for receiver/ext
// process)
sem_init(&sem_endRTAcquisition, 1, 0);
bool receiver = Parallel(&slsDetector::getUseReceiverFlag, {}).squash(false);
progressIndex = 0;
setJoinThreadFlag(false);
bool receiver = Parallel(&slsDetector::getUseReceiverFlag, {}).squash(false);
progressIndex = 0;
setJoinThreadFlag(false);
// verify receiver is idle
if (receiver) {
if (Parallel(&slsDetector::getReceiverStatus, {}).squash(ERROR) != IDLE) {
// verify receiver is idle
if (receiver) {
if (Parallel(&slsDetector::getReceiverStatus, {}).squash(ERROR) != IDLE) {
Parallel(&slsDetector::stopReceiver, {});
}
}
setTotalProgress();
startProcessingThread();
// start receiver
if (receiver) {
Parallel(&slsDetector::startReceiver, {});
// let processing thread listen to these packets
sem_post(&sem_newRTAcquisition);
}
// start and read all
try {
if (multi_shm()->multiDetectorType == EIGER) {
Parallel(&slsDetector::prepareAcquisition, {});
}
Parallel(&slsDetector::startAndReadAll, {});
} catch (...) {
Parallel(&slsDetector::stopReceiver, {});
throw;
}
}
setTotalProgress();
startProcessingThread();
// stop receiver
if (receiver) {
Parallel(&slsDetector::stopReceiver, {});
if (dataReady != nullptr) {
sem_wait(&sem_endRTAcquisition); // waits for receiver's
}
// external process to be
// done sending data to gui
// start receiver
if (receiver) {
Parallel(&slsDetector::startReceiver, {});
// let processing thread listen to these packets
Parallel(&slsDetector::incrementFileIndex, {});
}
// waiting for the data processing thread to finish!
setJoinThreadFlag(true);
sem_post(&sem_newRTAcquisition);
}
dataProcessingThread.join();
// start and read all
if (multi_shm()->multiDetectorType == EIGER) {
Parallel(&slsDetector::prepareAcquisition, {});
}
Parallel(&slsDetector::startAndReadAll, {});
// stop receiver
if (receiver) {
Parallel(&slsDetector::stopReceiver, {});
if (dataReady != nullptr) {
sem_wait(&sem_endRTAcquisition); // waits for receiver's
if (acquisition_finished != nullptr) {
// same status for all, else error
int status = static_cast<int>(ERROR);
auto t = Parallel(&slsDetector::getRunStatus, {});
if (t.equal())
status = t.front();
acquisition_finished(getCurrentProgress(), status,
acqFinished_p);
}
// external process to be
// done sending data to gui
Parallel(&slsDetector::incrementFileIndex, {});
sem_destroy(&sem_newRTAcquisition);
sem_destroy(&sem_endRTAcquisition);
clock_gettime(CLOCK_REALTIME, &end);
FILE_LOG(logDEBUG1) << "Elapsed time for acquisition:"
<< ((end.tv_sec - begin.tv_sec) +
(end.tv_nsec - begin.tv_nsec) / 1000000000.0)
<< " seconds";
} catch (...) {
setAcquiringFlag(false);
throw;
}
// waiting for the data processing thread to finish!
setJoinThreadFlag(true);
sem_post(&sem_newRTAcquisition);
dataProcessingThread.join();
if (acquisition_finished != nullptr) {
// same status for all, else error
int status = static_cast<int>(ERROR);
auto t = Parallel(&slsDetector::getRunStatus, {});
if (t.equal())
status = t.front();
acquisition_finished(getCurrentProgress(), status,
acqFinished_p);
}
sem_destroy(&sem_newRTAcquisition);
sem_destroy(&sem_endRTAcquisition);
clock_gettime(CLOCK_REALTIME, &end);
FILE_LOG(logDEBUG1) << "Elapsed time for acquisition:"
<< ((end.tv_sec - begin.tv_sec) +
(end.tv_nsec - begin.tv_nsec) / 1000000000.0)
<< " seconds";
setAcquiringFlag(false);
return OK;
}

View File

@ -17,7 +17,7 @@ class detectorData;
#include <vector>
#define MULTI_SHMAPIVERSION 0x190809
#define MULTI_SHMVERSION 0x190814
#define MULTI_SHMVERSION 0x190819
#define SHORT_STRING_LENGTH 50
#define DATE_LENGTH 30
@ -462,7 +462,6 @@ class multiSlsDetector : public virtual slsDetectorDefs {
bool jointhread{false};
/** the data processing thread */
// pthread_t dataProcessingThread;
std::thread dataProcessingThread;
/** detector data packed for the gui */

View File

@ -1,12 +1,12 @@
#include "slsDetector.h"
#include "ClientSocket.h"
#include "SharedMemory.h"
#include "ToString.h"
#include "file_utils.h"
#include "network_utils.h"
#include "sls_detector_exceptions.h"
#include "string_utils.h"
#include "versionAPI.h"
#include "ToString.h"
#include <arpa/inet.h>
#include <array>
@ -323,7 +323,8 @@ void slsDetector::initializeDetectorStructure(detectorType type) {
sls::strcpy_safe(shm()->settingsDir, getenv("HOME"));
shm()->roi.xmin = -1;
shm()->roi.xmax = -1;
shm()->adcEnableMask = BIT32_MASK;
shm()->adcEnableMaskOneGiga = BIT32_MASK;
shm()->adcEnableMaskTenGiga = BIT32_MASK;
shm()->roMode = ANALOG_ONLY;
shm()->currentSettings = UNINITIALIZED;
shm()->currentThresholdEV = -1;
@ -334,17 +335,17 @@ void slsDetector::initializeDetectorStructure(detectorType type) {
sls::strcpy_safe(shm()->rxHostname, "none");
shm()->rxTCPPort = DEFAULT_PORTNO + 2;
shm()->useReceiverFlag = false;
shm()->tenGigaEnable = 0;
shm()->flippedDataX = 0;
shm()->tenGigaEnable = false;
shm()->flippedDataX = false;
shm()->zmqport = DEFAULT_ZMQ_CL_PORTNO +
(detId * ((shm()->myDetectorType == EIGER) ? 2 : 1));
shm()->rxZmqport = DEFAULT_ZMQ_RX_PORTNO +
(detId * ((shm()->myDetectorType == EIGER) ? 2 : 1));
shm()->rxUpstream = false;
shm()->rxReadFreq = 1;
shm()->zmqip = 0u;
shm()->rxZmqip = 0u;
shm()->gappixels = 0u;
shm()->zmqip = IpAddr{};
shm()->rxZmqip = IpAddr{};
shm()->gappixels = 0U;
memset(shm()->rxAdditionalJsonHeader, 0, MAX_STR_LENGTH);
shm()->rxFrameDiscardMode = NO_DISCARD;
shm()->rxFramePadding = true;
@ -552,12 +553,12 @@ void slsDetector::updateNumberOfChannels() {
// analog channels (normal, analog/digital readout)
if (shm()->roMode == slsDetectorDefs::ANALOG_ONLY ||
shm()->roMode == slsDetectorDefs::ANALOG_AND_DIGITAL) {
uint32_t mask = shm()->adcEnableMask;
uint32_t mask = shm()->tenGigaEnable ? shm()->adcEnableMaskTenGiga : shm()->adcEnableMaskOneGiga;
if (mask == BIT32_MASK) {
nachans = 32;
} else {
for (int ich = 0; ich < 32; ++ich) {
if ((mask & (1 << ich)) != 0u)
if ((mask & (1 << ich)) != 0U)
++nachans;
}
}
@ -577,7 +578,7 @@ void slsDetector::updateNumberOfChannels() {
}
slsDetectorDefs::xy slsDetector::getNumberOfChannels() const {
slsDetectorDefs::xy coord;
slsDetectorDefs::xy coord{};
coord.x = (shm()->nChan.x * shm()->nChip.x +
shm()->gappixels * shm()->nGappixels.x);
coord.y = (shm()->nChan.y * shm()->nChip.y +
@ -590,7 +591,7 @@ bool slsDetector::getQuad() {
FILE_LOG(logDEBUG1) << "Getting Quad Type";
sendToDetector(F_GET_QUAD, nullptr, retval);
FILE_LOG(logDEBUG1) << "Quad Type :" << retval;
return (retval == 0 ? false : true);
return retval != 0;
}
void slsDetector::setQuad(const bool enable) {
@ -685,11 +686,11 @@ bool slsDetector::lockServer(int lock) {
FILE_LOG(logDEBUG1) << "Setting detector server lock to " << lock;
sendToDetector(F_LOCK_SERVER, lock, retval);
FILE_LOG(logDEBUG1) << "Lock: " << retval;
return (retval == 1 ? true : false);
return retval == 1;
}
sls::IpAddr slsDetector::getLastClientIP() {
sls::IpAddr retval = 0u;
sls::IpAddr retval;
FILE_LOG(logDEBUG1) << "Getting last client ip to detector server";
sendToDetector(F_GET_LAST_CLIENT_IP, nullptr, retval);
FILE_LOG(logDEBUG1) << "Last client IP to detector: " << retval;
@ -708,7 +709,7 @@ void slsDetector::execCommand(const std::string &cmd) {
sls::strcpy_safe(arg, cmd.c_str());
FILE_LOG(logDEBUG1) << "Sending command to detector " << arg;
sendToDetector(F_EXEC_COMMAND, arg, retval);
if (strlen(retval) != 0u) {
if (strlen(retval) != 0U) {
FILE_LOG(logINFO) << "Detector " << detId << " returned:\n" << retval;
}
}
@ -721,7 +722,7 @@ void slsDetector::updateCachedDetectorVariables() {
FORCE_UPDATE) {
int n = 0, i32 = 0;
int64_t i64 = 0;
sls::IpAddr lastClientIP = 0u;
sls::IpAddr lastClientIP;
n += client.Receive(&lastClientIP, sizeof(lastClientIP));
FILE_LOG(logDEBUG1)
<< "Updating detector last modified by " << lastClientIP;
@ -771,14 +772,27 @@ void slsDetector::updateCachedDetectorVariables() {
shm()->roi.xmax = i32;
}
// 10GbE
if (shm()->myDetectorType == EIGER ||
shm()->myDetectorType == CHIPTESTBOARD ||
shm()->myDetectorType == MOENCH) {
n += client.Receive(&i32, sizeof(i32));
shm()->tenGigaEnable = static_cast<bool>(i32);
}
if (shm()->myDetectorType == CHIPTESTBOARD ||
shm()->myDetectorType == MOENCH) {
// adcmask
// 1gb adcmask
uint32_t u32 = 0;
n += client.Receive(&u32, sizeof(u32));
shm()->adcEnableMask = u32;
shm()->adcEnableMaskOneGiga = u32;
// 10gb adcmask
n += client.Receive(&u32, sizeof(u32));
shm()->adcEnableMaskTenGiga = u32;
if (shm()->myDetectorType == MOENCH)
setAdditionalJsonParameter("adcmask", std::to_string(u32));
setAdditionalJsonParameter("adcmask", std::to_string(shm()->tenGigaEnable ? shm()->adcEnableMaskTenGiga : shm()->adcEnableMaskOneGiga));
// update #nchan, as it depends on #samples, adcmask,
updateNumberOfChannels();
@ -1598,7 +1612,7 @@ bool slsDetector::getStoreInRamMode() {
}
void slsDetector::setReadoutMode(const slsDetectorDefs::readoutMode mode) {
uint32_t arg = static_cast<uint32_t>(mode);
auto arg = static_cast<uint32_t>(mode);
FILE_LOG(logDEBUG1) << "Setting readout mode to " << arg;
sendToDetector(F_SET_READOUT_MODE, arg, nullptr);
shm()->roMode = mode;
@ -1706,36 +1720,6 @@ std::string slsDetector::setReceiverHostname(const std::string &receiverIP) {
shm()->useReceiverFlag = true;
checkReceiverVersionCompatibility();
FILE_LOG(logDEBUG)
<< "detector type:"
<< (ToString(shm()->myDetectorType))
<< "\ndetector id:" << detId
<< "\ndetector hostname:" << shm()->hostname
<< "\nfile path:" << shm()->rxFilePath
<< "\nfile name:" << shm()->rxFileName
<< "\nfile index:" << shm()->rxFileIndex
<< "\nfile format:" << shm()->rxFileFormat
<< "\nr_framesperfile:" << shm()->rxFramesPerFile
<< "\nr_discardpolicy:" << shm()->rxFrameDiscardMode
<< "\nr_padding:" << shm()->rxFramePadding
<< "\nwrite enable:" << shm()->rxFileWrite
<< "\nmaster write enable:" << shm()->rxMasterFileWrite
<< "\noverwrite enable:" << shm()->rxFileOverWrite
<< "\ndynamic range:" << shm()->dynamicRange
<< "\nflippeddatax:" << (shm()->flippedDataX)
<< "\nactivated: " << shm()->activated
<< "\nreceiver deactivated padding: " << shm()->rxPadDeactivatedModules
<< "\nsilent Mode:" << shm()->rxSilentMode
<< "\n10GbE:" << shm()->tenGigaEnable
<< "\nGap pixels: " << shm()->gappixels
<< "\nr_readfreq:" << shm()->rxReadFreq
<< "\nrx streaming port:" << shm()->rxZmqport
<< "\nrx streaming source ip:" << shm()->rxZmqip
<< "\nrx additional json header:" << shm()->rxAdditionalJsonHeader
<< "\nrx_datastream:" << enableDataStreamingFromReceiver(-1)
<< "\nrx_dbitlistsize:" << shm()->rxDbitList.size()
<< "\nrx_DbitOffset:" << shm()->rxDbitOffset << std::endl;
if (setDetectorType(shm()->myDetectorType) != GENERIC) {
sendMultiDetectorSize();
setDetectorId();
@ -1780,16 +1764,17 @@ std::string slsDetector::setReceiverHostname(const std::string &receiverIP) {
setDeactivatedRxrPaddingMode(
static_cast<int>(shm()->rxPadDeactivatedModules));
enableGapPixels(shm()->gappixels);
enableTenGigabitEthernet(shm()->tenGigaEnable);
enableTenGigabitEthernet(static_cast<int>(shm()->tenGigaEnable));
setQuad(getQuad());
break;
case CHIPTESTBOARD:
setNumberOfAnalogSamples(getNumberOfAnalogSamples());
setNumberOfDigitalSamples(getNumberOfDigitalSamples());
enableTenGigabitEthernet(shm()->tenGigaEnable);
enableTenGigabitEthernet(static_cast<int>(shm()->tenGigaEnable));
setReadoutMode(shm()->roMode);
setADCEnableMask(shm()->adcEnableMask);
setADCEnableMask(shm()->adcEnableMaskOneGiga);
setTenGigaADCEnableMask(shm()->adcEnableMaskTenGiga);
setReceiverDbitOffset(shm()->rxDbitOffset);
setReceiverDbitList(shm()->rxDbitList);
break;
@ -1797,14 +1782,19 @@ std::string slsDetector::setReceiverHostname(const std::string &receiverIP) {
case MOENCH:
setNumberOfAnalogSamples(getNumberOfAnalogSamples());
setNumberOfDigitalSamples(getNumberOfDigitalSamples());
enableTenGigabitEthernet(shm()->tenGigaEnable);
setADCEnableMask(shm()->adcEnableMask);
enableTenGigabitEthernet(static_cast<int>(shm()->tenGigaEnable));
setADCEnableMask(shm()->adcEnableMaskOneGiga);
setTenGigaADCEnableMask(shm()->adcEnableMaskTenGiga);
break;
case GOTTHARD:
sendROItoReceiver();
break;
case MYTHEN3:
sendNumberofCounterstoReceiver(getCounterMask());
break;
default:
break;
}
@ -1835,7 +1825,7 @@ void slsDetector::setSourceUDPMAC(const sls::MacAddr mac) {
}
sls::MacAddr slsDetector::getSourceUDPMAC() {
sls::MacAddr retval(0lu);
sls::MacAddr retval(0LU);
FILE_LOG(logDEBUG1) << "Getting source udp mac";
sendToDetector(F_GET_SOURCE_UDP_MAC, nullptr, retval);
FILE_LOG(logDEBUG1) << "Source udp mac: " << retval;
@ -1851,7 +1841,7 @@ void slsDetector::setSourceUDPMAC2(const sls::MacAddr mac) {
}
sls::MacAddr slsDetector::getSourceUDPMAC2() {
sls::MacAddr retval(0lu);
sls::MacAddr retval(0LU);
FILE_LOG(logDEBUG1) << "Getting source udp mac2";
sendToDetector(F_GET_SOURCE_UDP_MAC2, nullptr, retval);
FILE_LOG(logDEBUG1) << "Source udp mac2: " << retval;
@ -1868,7 +1858,7 @@ void slsDetector::setSourceUDPIP(const IpAddr ip) {
}
sls::IpAddr slsDetector::getSourceUDPIP() {
sls::IpAddr retval(0u);
sls::IpAddr retval(0U);
FILE_LOG(logDEBUG1) << "Getting source udp ip";
sendToDetector(F_GET_SOURCE_UDP_IP, nullptr, retval);
FILE_LOG(logDEBUG1) << "Source udp ip: " << retval;
@ -1885,7 +1875,7 @@ void slsDetector::setSourceUDPIP2(const IpAddr ip) {
}
sls::IpAddr slsDetector::getSourceUDPIP2() {
sls::IpAddr retval(0u);
sls::IpAddr retval(0U);
FILE_LOG(logDEBUG1) << "Getting source udp ip2";
sendToDetector(F_GET_SOURCE_UDP_IP2, nullptr, retval);
FILE_LOG(logDEBUG1) << "Source udp ip2: " << retval;
@ -1899,7 +1889,7 @@ void slsDetector::setDestinationUDPIP(const IpAddr ip) {
}
sendToDetector(F_SET_DEST_UDP_IP, ip, nullptr);
if (shm()->useReceiverFlag) {
sls::MacAddr retval(0lu);
sls::MacAddr retval(0LU);
sendToReceiver(F_SET_RECEIVER_UDP_IP, ip, retval);
FILE_LOG(logINFO) << "Setting destination udp mac to " << retval;
sendToDetector(F_SET_DEST_UDP_MAC, retval, nullptr);
@ -1907,7 +1897,7 @@ void slsDetector::setDestinationUDPIP(const IpAddr ip) {
}
sls::IpAddr slsDetector::getDestinationUDPIP() {
sls::IpAddr retval(0u);
sls::IpAddr retval(0U);
FILE_LOG(logDEBUG1) << "Getting destination udp ip";
sendToDetector(F_GET_DEST_UDP_IP, nullptr, retval);
FILE_LOG(logDEBUG1) << "Destination udp ip: " << retval;
@ -1918,7 +1908,7 @@ void slsDetector::updateRxDestinationUDPIP() {
auto ip = getDestinationUDPIP();
if (ip == 0) {
// Hostname could be ip try to decode otherwise look up the hostname
ip = shm()->rxHostname;
ip = sls::IpAddr{shm()->rxHostname};
if (ip == 0) {
ip = HostnameToIp(shm()->rxHostname);
}
@ -1935,7 +1925,7 @@ void slsDetector::setDestinationUDPIP2(const IpAddr ip) {
sendToDetector(F_SET_DEST_UDP_IP2, ip, nullptr);
if (shm()->useReceiverFlag) {
sls::MacAddr retval(0lu);
sls::MacAddr retval(0LU);
sendToReceiver(F_SET_RECEIVER_UDP_IP2, ip, retval);
FILE_LOG(logINFO) << "Setting destination udp mac2 to " << retval;
sendToDetector(F_SET_DEST_UDP_MAC2, retval, nullptr);
@ -1943,7 +1933,7 @@ void slsDetector::setDestinationUDPIP2(const IpAddr ip) {
}
sls::IpAddr slsDetector::getDestinationUDPIP2() {
sls::IpAddr retval(0u);
sls::IpAddr retval(0U);
FILE_LOG(logDEBUG1) << "Getting destination udp ip2";
sendToDetector(F_GET_DEST_UDP_IP2, nullptr, retval);
FILE_LOG(logDEBUG1) << "Destination udp ip2: " << retval;
@ -1954,7 +1944,7 @@ void slsDetector::updateRxDestinationUDPIP2() {
auto ip = getDestinationUDPIP2();
if (ip == 0) {
// Hostname could be ip try to decode otherwise look up the hostname
ip = shm()->rxHostname;
ip = sls::IpAddr{shm()->rxHostname};
if (ip == 0) {
ip = HostnameToIp(shm()->rxHostname);
}
@ -1973,7 +1963,7 @@ void slsDetector::setDestinationUDPMAC(const MacAddr mac) {
}
sls::MacAddr slsDetector::getDestinationUDPMAC() {
sls::MacAddr retval(0lu);
sls::MacAddr retval(0LU);
FILE_LOG(logDEBUG1) << "Getting destination udp mac";
sendToDetector(F_GET_DEST_UDP_MAC, nullptr, retval);
FILE_LOG(logDEBUG1) << "Destination udp mac: " << retval;
@ -1990,7 +1980,7 @@ void slsDetector::setDestinationUDPMAC2(const MacAddr mac) {
}
sls::MacAddr slsDetector::getDestinationUDPMAC2() {
sls::MacAddr retval(0lu);
sls::MacAddr retval(0LU);
FILE_LOG(logDEBUG1) << "Getting destination udp mac2";
sendToDetector(F_GET_DEST_UDP_MAC2, nullptr, retval);
FILE_LOG(logDEBUG1) << "Destination udp mac2: " << retval;
@ -2126,7 +2116,7 @@ void slsDetector::updateReceiverStreamingIP() {
auto ip = getReceiverStreamingIP();
if (ip == 0) {
// Hostname could be ip try to decode otherwise look up the hostname
ip = shm()->rxHostname;
ip = sls::IpAddr{shm()->rxHostname};
if (ip == 0) {
ip = HostnameToIp(shm()->rxHostname);
}
@ -2140,7 +2130,7 @@ bool slsDetector::getTenGigaFlowControl() {
int retval = -1;
sendToDetector(F_GET_TEN_GIGA_FLOW_CONTROL, nullptr, retval);
FILE_LOG(logDEBUG1) << "ten giga flow control :" << retval;
return retval == 1 ? true : false;
return retval == 1;
}
void slsDetector::setTenGigaFlowControl(bool enable) {
@ -2262,7 +2252,7 @@ std::string slsDetector::setAdditionalJsonParameter(const std::string &key,
// key not found, append key value pair
else {
if (header.length() != 0u) {
if (header.length() != 0U) {
header.append(",");
}
header.append(keyLiteral + valueLiteral);
@ -2275,7 +2265,7 @@ std::string slsDetector::setAdditionalJsonParameter(const std::string &key,
std::string slsDetector::getAdditionalJsonParameter(const std::string &key) {
// additional json header is empty
if (strlen(shm()->rxAdditionalJsonHeader) == 0u)
if (strlen(shm()->rxAdditionalJsonHeader) == 0U)
return std::string();
// add quotations before and after the key value
@ -2589,20 +2579,20 @@ void slsDetector::setADCEnableMask(uint32_t mask) {
FILE_LOG(logDEBUG1) << "Setting ADC Enable mask to 0x" << std::hex << arg
<< std::dec;
sendToDetector(F_SET_ADC_ENABLE_MASK, &arg, sizeof(arg), nullptr, 0);
shm()->adcEnableMask = mask;
shm()->adcEnableMaskOneGiga = mask;
// update #nchan, as it depends on #samples, adcmask,
updateNumberOfChannels();
// send to processor
if (shm()->myDetectorType == MOENCH)
if (shm()->myDetectorType == MOENCH && !shm()->tenGigaEnable)
setAdditionalJsonParameter("adcmask",
std::to_string(shm()->adcEnableMask));
std::to_string(shm()->adcEnableMaskOneGiga));
if (shm()->useReceiverFlag) {
int fnum = F_RECEIVER_SET_ADC_MASK;
int retval = -1;
mask = shm()->adcEnableMask;
mask = shm()->adcEnableMaskOneGiga;
FILE_LOG(logDEBUG1) << "Setting ADC Enable mask to 0x" << std::hex
<< mask << std::dec << " in receiver";
sendToReceiver(fnum, mask, retval);
@ -2613,10 +2603,45 @@ uint32_t slsDetector::getADCEnableMask() {
uint32_t retval = -1;
FILE_LOG(logDEBUG1) << "Getting ADC Enable mask";
sendToDetector(F_GET_ADC_ENABLE_MASK, nullptr, 0, &retval, sizeof(retval));
shm()->adcEnableMask = retval;
shm()->adcEnableMaskOneGiga = retval;
FILE_LOG(logDEBUG1) << "ADC Enable Mask: 0x" << std::hex << retval
<< std::dec;
return shm()->adcEnableMask;
return shm()->adcEnableMaskOneGiga;
}
void slsDetector::setTenGigaADCEnableMask(uint32_t mask) {
uint32_t arg = mask;
FILE_LOG(logDEBUG1) << "Setting 10Gb ADC Enable mask to 0x" << std::hex << arg
<< std::dec;
sendToDetector(F_SET_ADC_ENABLE_MASK_10G, &arg, sizeof(arg), nullptr, 0);
shm()->adcEnableMaskTenGiga = mask;
// update #nchan, as it depends on #samples, adcmask,
updateNumberOfChannels();
// send to processor
if (shm()->myDetectorType == MOENCH && shm()->tenGigaEnable)
setAdditionalJsonParameter("adcmask",
std::to_string(shm()->adcEnableMaskTenGiga));
if (shm()->useReceiverFlag) {
int fnum = F_RECEIVER_SET_ADC_MASK_10G;
int retval = -1;
mask = shm()->adcEnableMaskTenGiga;
FILE_LOG(logDEBUG1) << "Setting 10Gb ADC Enable mask to 0x" << std::hex
<< mask << std::dec << " in receiver";
sendToReceiver(fnum, mask, retval);
}
}
uint32_t slsDetector::getTenGigaADCEnableMask() {
uint32_t retval = -1;
FILE_LOG(logDEBUG1) << "Getting 10Gb ADC Enable mask";
sendToDetector(F_GET_ADC_ENABLE_MASK_10G, nullptr, 0, &retval, sizeof(retval));
shm()->adcEnableMaskTenGiga = retval;
FILE_LOG(logDEBUG1) << "10Gb ADC Enable Mask: 0x" << std::hex << retval
<< std::dec;
return shm()->adcEnableMaskTenGiga;
}
void slsDetector::setADCInvert(uint32_t value) {
@ -2657,7 +2682,7 @@ int slsDetector::setExternalSampling(int value) {
int slsDetector::getExternalSampling() { return setExternalSampling(-1); }
void slsDetector::setReceiverDbitList(std::vector<int> list) {
void slsDetector::setReceiverDbitList(const std::vector<int>& list) {
FILE_LOG(logDEBUG1) << "Setting Receiver Dbit List";
if (list.size() > 64) {
@ -2742,23 +2767,22 @@ bool slsDetector::setDeactivatedRxrPaddingMode(int padding) {
return shm()->rxPadDeactivatedModules;
}
int slsDetector::getFlippedDataX() const { return shm()->flippedDataX; }
bool slsDetector::getFlippedDataX() const { return shm()->flippedDataX; }
int slsDetector::setFlippedDataX(int value) {
void slsDetector::setFlippedDataX(int value) {
// replace get with shm value (write to shm right away as it is a det value,
// not rx value)
if (value > -1) {
shm()->flippedDataX = (value > 0) ? 1 : 0;
shm()->flippedDataX = (value > 0);
}
int retval = -1;
int arg = shm()->flippedDataX;
int arg = static_cast<int>(shm()->flippedDataX);
FILE_LOG(logDEBUG1) << "Setting flipped data across x axis with value: "
<< arg;
if (shm()->useReceiverFlag) {
sendToReceiver(F_SET_FLIPPED_DATA_RECEIVER, arg, retval);
FILE_LOG(logDEBUG1) << "Flipped data:" << retval;
}
return shm()->flippedDataX;
}
int slsDetector::setAllTrimbits(int val) {
@ -2787,7 +2811,7 @@ int slsDetector::enableGapPixels(int val) {
return shm()->gappixels;
}
int slsDetector::setTrimEn(std::vector<int> energies) {
int slsDetector::setTrimEn(const std::vector<int>& energies) {
if (shm()->myDetectorType != EIGER) {
throw RuntimeError("Not implemented for this detector.");
}
@ -3128,7 +3152,7 @@ int slsDetector::lockReceiver(int lock) {
}
sls::IpAddr slsDetector::getReceiverLastClientIP() const {
sls::IpAddr retval = 0u;
sls::IpAddr retval;
FILE_LOG(logDEBUG1) << "Getting last client ip to receiver server";
if (shm()->useReceiverFlag) {
sendToReceiver(F_GET_LAST_RECEIVER_CLIENT_IP, nullptr, retval);
@ -3166,7 +3190,7 @@ void slsDetector::updateCachedReceiverVariables() const {
int n = 0, i32 = 0;
int64_t i64 = 0;
char cstring[MAX_STR_LENGTH]{};
IpAddr ip = 0u;
IpAddr ip;
n += receiver.Receive(&ip, sizeof(ip));
FILE_LOG(logDEBUG1)
@ -3481,6 +3505,9 @@ std::vector<uint64_t> slsDetector::getNumMissingPackets() const {
throw RuntimeError("Receiver " + std::to_string(detId) +
" returned error: " + std::string(mess));
} else {
if (ret == FORCE_UPDATE) {
updateCachedReceiverVariables();
}
int nports = -1;
client.Receive(&nports, sizeof(nports));
uint64_t mp[nports];
@ -3595,15 +3622,15 @@ bool slsDetector::enableDataStreamingFromReceiver(int enable) {
return shm()->rxUpstream;
}
int slsDetector::enableTenGigabitEthernet(int value) {
bool slsDetector::enableTenGigabitEthernet(int value) {
int retval = -1;
FILE_LOG(logDEBUG1) << "Enabling / Disabling 10Gbe: " << value;
sendToDetector(F_ENABLE_TEN_GIGA, value, retval);
FILE_LOG(logDEBUG1) << "10Gbe: " << retval;
shm()->tenGigaEnable = retval;
shm()->tenGigaEnable = static_cast<bool>(retval);
if (shm()->useReceiverFlag) {
retval = -1;
value = shm()->tenGigaEnable;
value = static_cast<int>(shm()->tenGigaEnable);
FILE_LOG(logDEBUG1) << "Sending 10Gbe enable to receiver: " << value;
sendToReceiver(F_ENABLE_RECEIVER_TEN_GIGA, value, retval);
FILE_LOG(logDEBUG1) << "Receiver 10Gbe enable: " << retval;
@ -3646,7 +3673,7 @@ void slsDetector::setPattern(const std::string &fname) {
uint64_t addr = 0;
FILE *fd = fopen(fname.c_str(), "r");
if (fd != nullptr) {
while (fread(&word, sizeof(word), 1, fd) != 0u) {
while (fread(&word, sizeof(word), 1, fd) != 0U) {
setPatternWord(addr, word); // TODO! (Erik) do we need to send
// pattern in 64bit chunks?
++addr;
@ -3838,6 +3865,27 @@ void slsDetector::setPipeline(int clkIndex, int value) {
sendToDetector(F_SET_PIPELINE, args, nullptr);
}
void slsDetector::setCounterMask(uint32_t countermask) {
FILE_LOG(logDEBUG1) << "Setting Counter mask to " << countermask;
sendToDetector(F_SET_COUNTER_MASK, countermask, nullptr);
sendNumberofCounterstoReceiver(countermask);
}
void slsDetector::sendNumberofCounterstoReceiver(uint32_t countermask) {
if (shm()->useReceiverFlag) {
int ncounters = __builtin_popcount(countermask);
FILE_LOG(logDEBUG1) << "Sending Reciver #counters: " << ncounters;
sendToReceiver(F_RECEIVER_SET_NUM_COUNTERS, ncounters, nullptr);
}
}
uint32_t slsDetector::getCounterMask() {
uint32_t retval = 0;
sendToDetector(F_GET_COUNTER_MASK, nullptr, retval);
FILE_LOG(logDEBUG1) << "Received counter mask: " << retval;
return retval;
}
sls_detector_module slsDetector::interpolateTrim(sls_detector_module *a,
sls_detector_module *b,

View File

@ -13,7 +13,7 @@
class ServerInterface;
#define SLS_SHMAPIVERSION 0x190726
#define SLS_SHMVERSION 0x191030
#define SLS_SHMVERSION 0x191127
/**
* @short structure allocated in shared memory to store detector settings for
@ -65,8 +65,11 @@ struct sharedSlsDetector {
/** roi */
slsDetectorDefs::ROI roi;
/** adc enable mask */
uint32_t adcEnableMask;
/** 1gb adc enable mask */
uint32_t adcEnableMaskOneGiga;
/** 10gb adc enable mask */
uint32_t adcEnableMaskTenGiga;
/** readout mode */
slsDetectorDefs::readoutMode roMode;
@ -100,10 +103,10 @@ struct sharedSlsDetector {
bool useReceiverFlag;
/** 10 Gbe enable*/
int tenGigaEnable;
bool tenGigaEnable;
/** flipped data across x or y axis */
int flippedDataX;
bool flippedDataX;
/** tcp port from gui/different process to receiver (only data) */
int zmqport;
@ -1172,6 +1175,18 @@ class slsDetector : public virtual slsDetectorDefs {
*/
uint32_t getADCEnableMask();
/**
* Set 10Gb ADC Enable Mask (CTB, Moench)
* @param mask ADC Enable mask
*/
void setTenGigaADCEnableMask(uint32_t mask);
/**
* Get 10Gb ADC Enable Mask (CTB, Moench)
* @returns ADC Enable mask
*/
uint32_t getTenGigaADCEnableMask();
/**
* Set ADC invert register (CTB, Moench)
* @param value ADC invert value
@ -1221,7 +1236,7 @@ class slsDetector : public virtual slsDetectorDefs {
* @param list external sampling source (Option: 0-63)
* @param detPos -1 for all detectors in list or specific detector position
*/
void setReceiverDbitList(std::vector<int> list);
void setReceiverDbitList(const std::vector<int>& list);
/**
* Get external sampling source (CTB only)
@ -1269,17 +1284,16 @@ class slsDetector : public virtual slsDetectorDefs {
/**
* Returns the enable if data will be flipped across x axis (Eiger)
* @returns 1 for flipped, else 0
* @returns if flipped across x axis
*/
int getFlippedDataX() const;
bool getFlippedDataX() const;
/**
* Sets the enable which determines if
* data will be flipped across x axis (Eiger)
* @param value 0 or 1 to reset/set or -1 to get value
* @returns enable flipped data across x axis
*/
int setFlippedDataX(int value = -1);
void setFlippedDataX(int value = -1);
/**
* Sets all the trimbits to a particular value (Eiger)
@ -1303,7 +1317,7 @@ class slsDetector : public virtual slsDetectorDefs {
* @param vector os trimmed energies
* @returns number of trim energies
*/
int setTrimEn(std::vector<int> energies = {});
int setTrimEn(const std::vector<int>& energies = {});
/**
* Returns a vector with the trimmed energies (Eiger)
@ -1694,7 +1708,7 @@ class slsDetector : public virtual slsDetectorDefs {
* @param i is -1 to get, 0 to disable and 1 to enable
* @returns if 10Gbe is enabled
*/
int enableTenGigabitEthernet(int value = -1);
bool enableTenGigabitEthernet(int value = -1);
/**
* Set/get receiver fifo depth
@ -1848,6 +1862,15 @@ class slsDetector : public virtual slsDetectorDefs {
/** [Ctb][Moench] */
void setPipeline(int clkIndex, int value);
/** [Mythen3] */
void setCounterMask(uint32_t countermask);
/** [Mythen3] */
void sendNumberofCounterstoReceiver(uint32_t countermask);
/** [Mythen3] */
uint32_t getCounterMask();
private:
/**

View File

@ -5,8 +5,10 @@ target_sources(tests PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-rx.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-eiger.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-jungfrau.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-mythen3.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdProxy-global.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-Result.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdLineParser.cpp
${CMAKE_CURRENT_SOURCE_DIR}/test-CmdParser.cpp
)
target_include_directories(tests PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../src>")

View File

@ -1,4 +1,4 @@
#include "CmdLineParser.h"
#include "CmdParser.h"
#include "catch.hpp"
#include <exception>
#include <string>
@ -9,11 +9,11 @@
// command for all depreciated commands
using vs = std::vector<std::string>;
using sls::CmdLineParser;
using sls::CmdParser;
SCENARIO("Construction", "[support]") {
GIVEN("A default constructed CmdLineParser") {
CmdLineParser p;
GIVEN("A default constructed CmdParser") {
CmdParser p;
THEN("The state of the object is valid") {
REQUIRE(p.detector_id() == -1);
REQUIRE(p.multi_id() == 0);
@ -26,8 +26,8 @@ SCENARIO("Construction", "[support]") {
}
SCENARIO("Parsing a string with the command line parser", "[support]") {
GIVEN("A CmdLineParser") {
CmdLineParser p;
GIVEN("A CmdParser") {
CmdParser p;
WHEN("Parsing an empty string") {
std::string s;
p.Parse(s);
@ -121,7 +121,7 @@ SCENARIO("Parsing a string with the command line parser", "[support]") {
SCENARIO("Parsing strings with -h or --help", "[support]") {
GIVEN("A parser") {
CmdLineParser p;
CmdParser p;
WHEN("Parsing a string with a command and help ") {
std::string s = "-h list";
@ -159,7 +159,7 @@ SCENARIO("Parsing strings with -h or --help", "[support]") {
}
TEST_CASE("Parsing consecutive strings resets not found det id"){
CmdLineParser p;
CmdParser p;
p.Parse("1:exptime 0.5");
REQUIRE(p.detector_id() == 1);
p.Parse("exptime 0.5");
@ -170,7 +170,7 @@ TEST_CASE("Parsing consecutive strings resets not found det id"){
}
TEST_CASE("Parsing consecutive strings resets not found multi id"){
CmdLineParser p;
CmdParser p;
p.Parse("1-1:exptime 0.5");
REQUIRE(p.multi_id() == 1);
p.Parse("1:exptime 0.5");
@ -183,7 +183,7 @@ TEST_CASE("Parse with no arguments results in no command and default id",
// first argument is the command used to call the binary
int argc = 1;
const char *const argv[]{"call"};
CmdLineParser p;
CmdParser p;
p.Parse(argc, argv);
REQUIRE(p.detector_id() == -1);
@ -197,7 +197,7 @@ TEST_CASE(
"[support]") {
int argc = 2;
const char *const argv[]{"caller", "vrf"};
CmdLineParser p;
CmdParser p;
p.Parse(argc, argv);
REQUIRE(p.detector_id() == -1);
@ -210,7 +210,7 @@ TEST_CASE("Parse a command with value but without client or detector id",
"[support]") {
int argc = 3;
const char *const argv[]{"caller", "vrf", "3000"};
CmdLineParser p;
CmdParser p;
p.Parse(argc, argv);
REQUIRE(p.detector_id() == -1);
@ -224,7 +224,7 @@ TEST_CASE("Decodes position") {
int argc = 2;
const char *const argv[]{"caller", "7:vrf"};
CmdLineParser p;
CmdParser p;
p.Parse(argc, argv);
REQUIRE(p.detector_id() == 7);
@ -236,7 +236,7 @@ TEST_CASE("Decodes position") {
TEST_CASE("Decodes double digit position", "[support]") {
int argc = 2;
const char *const argv[]{"caller", "73:vcmp"};
CmdLineParser p;
CmdParser p;
p.Parse(argc, argv);
REQUIRE(p.detector_id() == 73);
@ -248,7 +248,7 @@ TEST_CASE("Decodes double digit position", "[support]") {
TEST_CASE("Decodes position and id", "[support]") {
int argc = 2;
const char *const argv[]{"caller", "5-8:vrf"};
CmdLineParser p;
CmdParser p;
p.Parse(argc, argv);
REQUIRE(p.detector_id() == 8);
@ -260,7 +260,7 @@ TEST_CASE("Decodes position and id", "[support]") {
TEST_CASE("Double digit id", "[support]") {
int argc = 2;
const char *const argv[]{"caller", "56-8:vrf"};
CmdLineParser p;
CmdParser p;
p.Parse(argc, argv);
REQUIRE(p.detector_id() == 8);
REQUIRE(p.multi_id() == 56);
@ -271,19 +271,19 @@ TEST_CASE("Double digit id", "[support]") {
TEST_CASE("Calling with wrong id throws invalid_argument", "[support]") {
int argc = 2;
const char *const argv[]{"caller", "asvldkn:vrf"};
CmdLineParser p;
CmdParser p;
CHECK_THROWS(p.Parse(argc, argv));
}
TEST_CASE("Calling with wrong client throws invalid_argument", "[support]") {
int argc = 2;
const char *const argv[]{"caller", "lki-3:vrf"};
CmdLineParser p;
CmdParser p;
CHECK_THROWS(p.Parse(argc, argv));
}
TEST_CASE("Build up argv", "[support]") {
CmdLineParser p;
CmdParser p;
REQUIRE(p.argv().empty());
REQUIRE(p.argv().data() == nullptr);

View File

@ -2,8 +2,10 @@
#include "Detector.h"
#include "catch.hpp"
#include "sls_detector_defs.h"
#include <array>
#include <sstream>
#include "test-CmdProxy-global.h"
#include "tests/globals.h"
#include "versionAPI.h"
@ -12,12 +14,263 @@ using sls::Detector;
using test::GET;
using test::PUT;
TEST_CASE("Eiger transmission delay", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
auto frame = det.getTransmissionDelayFrame();
auto left = det.getTransmissionDelayLeft();
auto right = det.getTransmissionDelayRight();
if (det_type == defs::EIGER) {
SECTION("txndelay_frame") {
std::ostringstream oss1, oss2;
proxy.Call("txndelay_frame", {"5000"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "txndelay_frame 5000\n");
proxy.Call("txndelay_frame", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "txndelay_frame 5000\n");
}
SECTION("txndelay_left") {
std::ostringstream oss1, oss2;
proxy.Call("txndelay_left", {"5000"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "txndelay_left 5000\n");
proxy.Call("txndelay_left", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "txndelay_left 5000\n");
}
SECTION("txndelay_right") {
std::ostringstream oss1, oss2;
proxy.Call("txndelay_right", {"5000"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "txndelay_right 5000\n");
proxy.Call("txndelay_right", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "txndelay_right 5000\n");
}
// Reset to previous values
for (int i = 0; i != det.size(); ++i) {
det.setTransmissionDelayFrame(frame[i]);
det.setTransmissionDelayLeft(left[i]);
det.setTransmissionDelayRight(right[i]);
}
}
}
TEST_CASE("dr", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER) {
// The only detector currently supporting setting dr
// is EIGER?
auto dr = det.getDynamicRange().squash();
std::array<int, 4> vals{4, 8, 16, 32};
for (const auto val : vals) {
std::ostringstream oss1, oss2;
proxy.Call("dr", {std::to_string(val)}, -1, PUT, oss1);
REQUIRE(oss1.str() == "dr " + std::to_string(val) + '\n');
proxy.Call("dr", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "dr " + std::to_string(val) + '\n');
}
det.setDynamicRange(dr);
} else {
// For the other detectors we should get an error message
// except for dr 16
REQUIRE_THROWS(proxy.Call("dr", {"4"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("dr", {"8"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("dr", {"32"}, -1, PUT));
std::ostringstream oss1, oss2;
proxy.Call("dr", {"16"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "dr 16\n");
proxy.Call("dr", {"16"}, -1, PUT, oss2);
REQUIRE(oss2.str() == "dr 16\n");
}
}
TEST_CASE("interruptsubframe", "[.cmd][!mayfail]") {
// TODO! Fix this for virtual server
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER) {
auto previous = det.getInterruptSubframe();
std::ostringstream oss1, oss2, oss3;
proxy.Call("interruptsubframe", {"1"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "interruptsubframe 1\n");
proxy.Call("interruptsubframe", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "interruptsubframe 1\n");
proxy.Call("interruptsubframe", {"0"}, -1, PUT, oss3);
REQUIRE(oss3.str() == "interruptsubframe 0\n");
for (int i = 0; i != det.size(); ++i) {
det.setInterruptSubframe(previous[i], {i});
}
} else {
REQUIRE_THROWS(proxy.Call("interruptsubframe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("interruptsubframe", {"1"}, -1, PUT));
}
}
TEST_CASE("overflow", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER) {
auto previous = det.getOverFlowMode();
std::ostringstream oss1, oss2, oss3;
proxy.Call("overflow", {"1"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "overflow 1\n");
proxy.Call("overflow", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "overflow 1\n");
proxy.Call("overflow", {"0"}, -1, PUT, oss3);
REQUIRE(oss3.str() == "overflow 0\n");
for (int i = 0; i != det.size(); ++i) {
det.setOverFlowMode(previous[i], {i});
}
} else {
REQUIRE_THROWS(proxy.Call("overflow", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("overflow", {"1"}, -1, PUT));
}
}
TEST_CASE("trimen", "[.cmd][.this]") {
// TODO! Also Mythen?
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER) {
auto previous = det.getTrimEnergies();
std::ostringstream oss1, oss2;
proxy.Call("trimen", {"4500", "5400", "6400"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "trimen [4500, 5400, 6400]\n");
proxy.Call("trimen", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "trimen [4500, 5400, 6400]\n");
for (int i = 0; i != det.size(); ++i) {
det.setTrimEnergies(previous[i], {i});
}
} else {
REQUIRE_THROWS(proxy.Call("trimen", {"4500", "5400", "6400"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("trimen", {}, -1, GET));
}
}
// TEST_CASE("threshold"{
// })
// TEST_CASE("activate", "[.cmd][.eiger]") {
// if (test::type == slsDetectorDefs::EIGER) {
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("0:activate 1", PUT,
// nullptr, oss)); REQUIRE(oss.str() == "activate 1\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("0:activate 1 nopadding",
// PUT, nullptr, oss)); REQUIRE(oss.str() == "activate 1
// nopadding\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("0:activate 0 padding",
// PUT, nullptr, oss)); REQUIRE(oss.str() == "activate 0
// padding\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("0:activate 0 nopadding",
// PUT, nullptr, oss)); REQUIRE(oss.str() == "activate 0
// nopadding\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("0:activate 1 padding",
// PUT, nullptr, oss)); REQUIRE(oss.str() == "activate 1
// padding\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("0:activate", GET,
// nullptr, oss)); REQUIRE(oss.str() == "activate 1 padding\n");
// }
// } else {
// REQUIRE_THROWS(multiSlsDetectorClient("activate", GET));
// }
// }
TEST_CASE("subexptime", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER) {
auto time = det.getSubExptime();
std::ostringstream oss1, oss2;
proxy.Call("subexptime", {"2.5us"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "subexptime 2.5us\n");
proxy.Call("subexptime", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "subexptime 2.5us\n");
for (int i = 0; i != det.size(); ++i) {
det.setSubExptime(time[i], {i});
}
} else {
REQUIRE_THROWS(proxy.Call("subexptime", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("subexptime", {"2.13"}, -1, PUT));
}
}
TEST_CASE("subdeadtime", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER) {
auto time = det.getSubDeadTime();
std::ostringstream oss1, oss2;
proxy.Call("subdeadtime", {"500us"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "subdeadtime 500us\n");
proxy.Call("subdeadtime", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "subdeadtime 500us\n");
for (int i = 0; i != det.size(); ++i) {
det.setSubDeadTime(time[i], {i});
}
} else {
REQUIRE_THROWS(proxy.Call("subdeadtime", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("subdeadtime", {"2.13"}, -1, PUT));
}
}
TEST_CASE("tengiga", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER || det_type == defs::CHIPTESTBOARD) {
auto tengiga = det.getTenGiga();
det.setTenGiga(false);
std::ostringstream oss1, oss2;
proxy.Call("tengiga", {"1"}, -1, PUT, oss1);
REQUIRE(oss1.str() == "tengiga 1\n");
proxy.Call("tengiga", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "tengiga 1\n");
for (int i = 0; i != det.size(); ++i) {
det.setTenGiga(tengiga[i], {i});
}
}
}
TEST_CASE("quad", "[.cmd]") {
// TODO! set and get once available in virtual detector
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER && det.size() == 1) {
if (det_type == defs::EIGER) {
// Quad only works with a single half module EIGER
std::ostringstream oss;
proxy.Call("quad", {}, -1, GET, oss);
@ -27,22 +280,6 @@ TEST_CASE("quad", "[.cmd]") {
}
}
void test_dac(defs::dacIndex index, const std::string &dacname, int dacvalue) {
Detector det;
CmdProxy proxy(&det);
std::ostringstream oss_set, oss_get;
auto dacstr = std::to_string(dacvalue);
auto previous = det.getDAC(index, false);
proxy.Call(dacname, {dacstr}, -1, PUT, oss_set);
REQUIRE(oss_set.str() == dacname + " " + dacstr + "\n");
proxy.Call(dacname, {}, -1, GET, oss_get);
REQUIRE(oss_set.str() == dacname + " " + dacstr + "\n");
// Reset all dacs to previous value
for (int i = 0; i != det.size(); ++i) {
det.setDAC(index, previous[i], false, {i});
}
}
TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
// vsvp, vtr, vrf, vrs, vsvn, vtgstv, vcmp_ll, vcmp_lr, vcal, vcmp_rl,
// rxb_rb, rxb_lb, vcmp_rr, vcp, vcn, vis, vthreshold
@ -96,6 +333,48 @@ TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
det.setDAC(defs::VCP, vcp[i], false, {i});
}
}
REQUIRE_THROWS(proxy.Call("vref_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascn_pb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascp_pb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vout_cm", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcasc_out", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vin_cm", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("ib_test_c", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vpreamp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vshaper", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vshaperneg", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vipre", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("viinsh", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vdcsh", {}, -1, GET));
// REQUIRE_THROWS(proxy.Call("vth1", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vth2", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vth3", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vpl", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vph", {}, -1, GET));
// REQUIRE_THROWS(proxy.Call("vtrim", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcassh", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcas", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vicin", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vipre_out", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_h_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp_fe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcom_cds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_restore", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_opa_1st", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_comp_fe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcom_adc1", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_l_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_cds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_cs", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_opa_fd", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcom_adc2", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_pixbuf", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vin_com", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vdd_prot", {}, -1, GET));
}
}
@ -122,7 +401,6 @@ TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
// REQUIRE(oss.str() == "trigger successful\n");
// }
// auto currentfnum = det.getStartingFrameNumber().tsquash(
// "inconsistent frame nr in test");
@ -134,49 +412,49 @@ TEST_CASE("Setting and reading back EIGER dacs", "[.cmd]") {
// REQUIRE(oss.str() == "timing auto\n");
// }
// }
// if(test::type != slsDetectorDefs::EIGER) {
// REQUIRE_THROWS(multiSlsDetectorClient("trigger", PUT));
// } else {
// // trigger
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("timing trigger", PUT,
// nullptr, oss)); REQUIRE(oss.str() == "timing trigger\n");
// }
// int startingfnum = 0;
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("startingfnum", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("startingfnum ")); startingfnum = std::stoi(s);
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("start", PUT, nullptr,
// oss)); REQUIRE(oss.str() == "start successful\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("status", GET,
// nullptr, oss)); REQUIRE(oss.str() != "status idle\n");
// REQUIRE(oss.str()
// != "status stopped\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("trigger", PUT,
// nullptr, oss)); REQUIRE(oss.str() == "trigger successful\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("stop", PUT));
// int currentfnum = 0;
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("startingfnum", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("startingfnum ")); currentfnum = std::stoi(s);
// }
// REQUIRE((startingfnum + 1) == currentfnum);
// if(test::type != slsDetectorDefs::EIGER) {
// REQUIRE_THROWS(multiSlsDetectorClient("trigger", PUT));
// } else {
// // trigger
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("timing trigger", PUT,
// nullptr, oss)); REQUIRE(oss.str() == "timing trigger\n");
// }
// int startingfnum = 0;
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("startingfnum", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("startingfnum ")); startingfnum = std::stoi(s);
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("start", PUT, nullptr,
// oss)); REQUIRE(oss.str() == "start successful\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("status", GET,
// nullptr, oss)); REQUIRE(oss.str() != "status idle\n");
// REQUIRE(oss.str()
// != "status stopped\n");
// }
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("trigger", PUT,
// nullptr, oss)); REQUIRE(oss.str() == "trigger successful\n");
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("stop", PUT));
// int currentfnum = 0;
// {
// std::ostringstream oss;
// REQUIRE_NOTHROW(multiSlsDetectorClient("startingfnum", GET,
// nullptr, oss)); std::string s = (oss.str()).erase (0,
// strlen("startingfnum ")); currentfnum = std::stoi(s);
// }
// REQUIRE((startingfnum + 1) == currentfnum);
// REQUIRE_NOTHROW(multiSlsDetectorClient("timing auto", PUT));
// }
// REQUIRE_NOTHROW(multiSlsDetectorClient("timing auto", PUT));
// }
// }

View File

@ -0,0 +1,27 @@
#include "test-CmdProxy-global.h"
#include "CmdProxy.h"
#include "Detector.h"
#include "catch.hpp"
#include "tests/globals.h"
using sls::CmdProxy;
using sls::Detector;
using test::GET;
using test::PUT;
void test_dac(defs::dacIndex index, const std::string &dacname, int dacvalue) {
Detector det;
CmdProxy proxy(&det);
std::ostringstream oss_set, oss_get;
auto dacstr = std::to_string(dacvalue);
auto previous = det.getDAC(index, false);
proxy.Call(dacname, {dacstr}, -1, PUT, oss_set);
REQUIRE(oss_set.str() == dacname + " " + dacstr + "\n");
proxy.Call(dacname, {}, -1, GET, oss_get);
REQUIRE(oss_get.str() == dacname + " " + dacstr + "\n");
// Reset all dacs to previous value
for (int i = 0; i != det.size(); ++i) {
det.setDAC(index, previous[i], false, {i});
}
}

View File

@ -0,0 +1,4 @@
#pragma once
#include "sls_detector_defs.h"
void test_dac(slsDetectorDefs::dacIndex index, const std::string &dacname, int dacvalue);

View File

@ -156,15 +156,6 @@ TEST_CASE("resetfpga", "[.cmd]") {
}
}
// TEST_CASE("resetfpga", "[.cmd][.ctb][.jungfrau]") {
// if (test::type == slsDetectorDefs::JUNGFRAU || test::type ==
// slsDetectorDefs::CHIPTESTBOARD) {
// ;//REQUIRE_NOTHROW(multiSlsDetectorClient("resetfpga", PUT));
// } else {
// REQUIRE_THROWS(multiSlsDetectorClient("resetfpga", GET));
// }
// }
// void test_dac(defs::dacIndex index, const std::string &dacname, int dacvalue)

View File

@ -0,0 +1,203 @@
#include "CmdProxy.h"
#include "Detector.h"
#include "catch.hpp"
#include "sls_detector_defs.h"
#include <sstream>
#include "Result.h"
#include "ToString.h"
#include "test-CmdProxy-global.h"
#include "tests/globals.h"
#include "versionAPI.h"
using sls::CmdProxy;
using sls::Detector;
using test::GET;
using test::PUT;
TEST_CASE("Setting and reading back MYTHEN3 dacs", "[.cmd][.dacs]") {
// vcassh, vth2, vshaper, vshaperneg, vipre_out, vth3, vth1,
// vicin, vcas, vpreamp, vpl, vipre, viinsh, vph, vtrim, vdcsh,
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::MYTHEN3) {
SECTION("vcassh") { test_dac(defs::CASSH, "vcassh", 1200); }
SECTION("vth2") { test_dac(defs::VTH2, "vth2", 2800); }
SECTION("vshaper") { test_dac(defs::SHAPER1, "vshaper", 1280); }
SECTION("vshaperneg") { test_dac(defs::SHAPER2, "vshaperneg", 2800); }
SECTION("vipre_out") { test_dac(defs::VIPRE_OUT, "vipre_out", 1220); }
SECTION("vth3") { test_dac(defs::VTH3, "vth3", 2800); }
SECTION("vth1") { test_dac(defs::THRESHOLD, "vth1", 2880); }
SECTION("vicin") { test_dac(defs::VICIN, "vicin", 1708); }
SECTION("vcas") { test_dac(defs::CAS, "vcas", 1800); }
SECTION("vpreamp") { test_dac(defs::PREAMP, "vpreamp", 1100); }
SECTION("vpl") { test_dac(defs::VPL, "vpl", 1100); }
SECTION("vipre") { test_dac(defs::VIPRE, "vipre", 2624); }
SECTION("viinsh") { test_dac(defs::VIINSH, "viinsh", 1708); }
SECTION("vph") { test_dac(defs::CALIBRATION_PULSE, "vph", 1712); }
SECTION("vtrim") { test_dac(defs::TRIMBIT_SIZE, "vtrim", 2800); }
SECTION("vdcsh") { test_dac(defs::VDCSH, "vdcsh", 800); }
REQUIRE_THROWS(proxy.Call("vsvp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vsvn", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vtr", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vrf", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vrs", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vtgstv", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_ll", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_lr", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcal", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_rl", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcmp_rr", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("rxb_rb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("rxb_lb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcn", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vis", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("iodelay", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascn_pb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcascp_pb", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vout_cm", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcasc_out", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vin_cm", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("ib_test_c", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_h_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp_fe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcom_cds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_restore", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_opa_1st", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_comp_fe", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcom_adc1", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_prech", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_l_adc", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vref_cds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_cs", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_opa_fd", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vcom_adc2", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_ds", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_comp", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vb_pixbuf", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vin_com", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("vdd_prot", {}, -1, GET));
}
}
TEST_CASE("clkfreq", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::MYTHEN3 || det_type == defs::GOTTHARD2) {
REQUIRE_THROWS(proxy.Call("clkfreq", {"0", "2"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("clkfreq", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("clkfreq", {"7"}, -1, GET));
auto value = det.getClockFrequency(0).squash(-1);
std::ostringstream oss_set, oss_get;
proxy.Call("clkfreq", {"0"}, -1, GET, oss_get);
REQUIRE(oss_get.str() == "clkfreq " + std::to_string(value) + "\n");
} else {
REQUIRE_THROWS(proxy.Call("clkfreq", {"0"}, -1, GET));
}
}
TEST_CASE("clkphase", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::MYTHEN3 || det_type == defs::GOTTHARD2) {
REQUIRE_THROWS(proxy.Call("clkphase", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("clkphase", {"7"}, -1, GET));
REQUIRE_THROWS(proxy.Call("clkphase", {"4"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("clkphase", {"7", "4"}, -1, PUT));
auto previous = det.getClockFrequency(0).squash(-1);
auto previous_string = std::to_string(previous);
std::ostringstream oss_set, oss_get, oss_get2;
proxy.Call("clkfreq", {"0", previous_string}, -1, PUT, oss_set);
REQUIRE(oss_set.str() == "clkfreq" + previous_string + "\n");
proxy.Call("clkfreq", {"0"}, -1, GET, oss_get);
REQUIRE(oss_get.str() == "clkfreq " + previous_string + "\n");
REQUIRE_NOTHROW(proxy.Call("clkphase", {"0", "deg"}, -1, GET));
} else {
REQUIRE_THROWS(proxy.Call("clkphase", {"0"}, -1, GET));
}
}
TEST_CASE("clkdiv", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::MYTHEN3 || det_type == defs::GOTTHARD2) {
REQUIRE_THROWS(proxy.Call("clkdiv", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("clkdiv", {"7"}, -1, GET));
REQUIRE_THROWS(proxy.Call("clkdiv", {"7", "4"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("clkdiv", {"7", "4"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("clkdiv", {"0", "1"}, -1, PUT));
auto previous = det.getClockDivider(0).squash(-1);
auto previous_string = std::to_string(previous);
std::ostringstream oss_set, oss_get;
proxy.Call("clkdiv", {"0", previous_string}, -1, PUT, oss_set);
REQUIRE(oss_set.str() == "clkdiv" + previous_string + "\n");
proxy.Call("clkdiv", {"0"}, -1, GET, oss_get);
REQUIRE(oss_get.str() == "clkdiv " + previous_string + "\n");
} else {
REQUIRE_THROWS(proxy.Call("clkdiv", {"0"}, -1, GET));
}
}
TEST_CASE("maxclkphaseshift", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::MYTHEN3 || det_type == defs::GOTTHARD2) {
REQUIRE_THROWS(proxy.Call("maxclkphaseshift", {"0", "2"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("maxclkphaseshift", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("maxclkphaseshift", {"7"}, -1, GET));
auto value = det.getMaxClockPhaseShift(0).squash(-1);
std::ostringstream oss_set, oss_get;
proxy.Call("maxclkphaseshift", {"0"}, -1, GET, oss_get);
REQUIRE(oss_get.str() ==
"maxclkphaseshift " + std::to_string(value) + "\n");
} else {
REQUIRE_THROWS(proxy.Call("maxclkphaseshift", {"0"}, -1, GET));
}
}
TEST_CASE("counters", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::MYTHEN3) {
REQUIRE_THROWS(proxy.Call("counters", {}, -1, PUT));
REQUIRE_THROWS(proxy.Call("counters", {"3"}, -1, GET));
REQUIRE_THROWS(proxy.Call("counters", {"0", "-1"}, -1, GET));
REQUIRE_THROWS(proxy.Call("counters", {"0", "1", "1"}, -1, GET));
auto mask = det.getCounterMask({0}).squash(-1);
std::vector<std::string> list_str;
for (int i = 0; i < 32; ++i) {
if (mask & (1 << i)) {
list_str.push_back(std::to_string(i));
}
}
std::ostringstream oss_set, oss_set2, oss_set3, oss_get;
proxy.Call("counters", {"0", "2", "1"}, -1, PUT, oss_set);
REQUIRE(oss_set.str() == "counters [0, 2, 1]\n");
proxy.Call("counters", {"0", "2"}, -1, PUT, oss_set2);
REQUIRE(oss_set2.str() == "counters [0, 2]\n");
// put back old value
proxy.Call("counters", list_str, -1, PUT, oss_set3);
REQUIRE(oss_set3.str() == "counters " + sls::ToString(list_str) + "\n");
proxy.Call("counters", {}, -1, GET, oss_get);
REQUIRE(oss_get.str() == "counters " + sls::ToString(list_str) + "\n");
} else {
REQUIRE_THROWS(proxy.Call("counters", {}, -1, GET));
}
}

View File

@ -13,11 +13,22 @@ using test::GET;
using test::PUT;
/*
This file should contain receiver specific tests use python/scripts/list_tested_cmd.py
to check if all commands are covered
This file should contain receiver specific tests use
python/scripts/list_tested_cmd.py to check if all commands are covered
*/
// TEST_CASE("A test", "[.hey]"){
// std::cout << "start\n";
// SECTION("a section"){
// std::cout << "s1\n";
// }
// SECTION("another section"){
// std::cout << "s2\n";
// }
// std::cout << "end\n";
// }
TEST_CASE("rx_hostname", "[.cmd]") {
// TODO! find a proper way to test, now we read out the rx_hostname
// and then put it to see that we don't crash
@ -26,6 +37,12 @@ TEST_CASE("rx_hostname", "[.cmd]") {
std::string hostname =
det.getRxHostname().tsquash("hostname must be same for test");
auto det_type = det.getDetectorType().squash();
sls::Result<sls::ns> time;
if (det_type == defs::EIGER) {
time = det.getSubDeadTime();
}
{
// disable receiver
std::ostringstream oss1, oss2;
@ -45,6 +62,14 @@ TEST_CASE("rx_hostname", "[.cmd]") {
proxy.Call("rx_hostname", {}, -1, GET, oss2);
REQUIRE(oss2.str() == "rx_hostname " + hostname + "\n");
}
//Bug rx_hostname could change subdeadtime
if (det_type == defs::EIGER) {
auto time2 = det.getSubDeadTime();
for (int i = 0; i != det.size(); ++i) {
REQUIRE(time[i].count() == time2[i].count());
}
}
}
TEST_CASE("rx_framescaught", "[.cmd]") {
@ -61,14 +86,15 @@ TEST_CASE("rx_framescaught", "[.cmd]") {
REQUIRE(oss.str() == "rx_framescaught 0\n");
}
// Currently disabled may activate if we have a stable env
// Now take one frame and see that we caught it
det.setNumberOfFrames(1);
det.acquire();
{
std::ostringstream oss;
proxy.Call("rx_framescaught", {}, -1, GET, oss);
REQUIRE(oss.str() == "rx_framescaught 1\n");
}
// det.setNumberOfFrames(1);
// det.acquire();
// {
// std::ostringstream oss;
// proxy.Call("rx_framescaught", {}, -1, GET, oss);
// REQUIRE(oss.str() == "rx_framescaught 1\n");
// }
}
TEST_CASE("rx_status", "[.cmd]") {
@ -224,12 +250,12 @@ TEST_CASE("rx_udpsocksize", "[.cmd]") {
{
std::ostringstream oss;
proxy.Call("rx_udpsocksize", {"4857600"}, -1, PUT, oss);
REQUIRE(oss.str() == "rx_udpsocksize 4857600\n");
REQUIRE(oss.str() >= "rx_udpsocksize 4857600\n");
}
{
std::ostringstream oss;
proxy.Call("rx_udpsocksize", {}, -1, GET, oss);
REQUIRE(oss.str() == "rx_udpsocksize 4857600\n");
REQUIRE(oss.str() >= "rx_udpsocksize 4857600\n");
}
}
@ -249,7 +275,7 @@ TEST_CASE("rx_realudpsocksize", "[.cmd]") {
proxy.Call("rx_realudpsocksize", {}, -1, GET, oss);
std::string s = (oss.str()).erase(0, strlen("rx_realudpsocksize "));
uint64_t rval = std::stol(s);
REQUIRE(rval == val * 2);
REQUIRE(rval >= val * 2);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -51,17 +51,15 @@ class BinaryFile : private virtual slsDetectorDefs, public File, public BinaryFi
/**
* Create file
* @returns OK or FAIL
*/
int CreateFile() override;
void CreateFile() override;
/**
* Create master file
* @param mfwenable master file write enable
* @param attr master file attributes
* @returns OK or FAIL
*/
int CreateMasterFile(bool mfwenable, masterAttributes& attr) override;
void CreateMasterFile(bool mfwenable, masterAttributes& attr) override;
/**
* Close Current File
@ -79,9 +77,8 @@ class BinaryFile : private virtual slsDetectorDefs, public File, public BinaryFi
* @param buffersize size of buffer
* @param fnum current image number
* @param nump number of packets caught
* @returns OK or FAIL
*/
int WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) override;
void WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) override;

View File

@ -98,23 +98,20 @@ class BinaryFileStatic {
* @param fname master file name
* @param owenable overwrite enable
* @param attr master file attributes
* @returns 0 for success and 1 for fail
*/
static int CreateMasterDataFile(FILE*& fd, std::string fname, bool owenable,
static void CreateMasterDataFile(FILE*& fd, std::string fname, bool owenable,
masterAttributes& attr)
{
if(!owenable){
if (NULL == (fd = fopen((const char *) fname.c_str(), "wx"))){
FILE_LOG(logERROR) << "Could not create binary master file "
"(without overwrite enable) " << fname;
fd = 0;
return 1;
throw sls::RuntimeError("Could not create binary master file "
"(without overwrite enable) " + fname);
}
}else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){
FILE_LOG(logERROR) << "Could not create binary master file "
"(with overwrite enable) " << fname;
fd = 0;
return 1;
throw sls::RuntimeError("Could not create binary master file "
"(with overwrite enable) " + fname);
}
time_t t = time(0);
char message[MAX_MASTER_FILE_LENGTH];
@ -182,16 +179,15 @@ class BinaryFileStatic {
attr.roiXmax,
ctime(&t));
if (strlen(message) > MAX_MASTER_FILE_LENGTH) {
FILE_LOG(logERROR) << "Master File Size " << strlen(message) <<
" is greater than max str size " << MAX_MASTER_FILE_LENGTH;
return 1;
throw sls::RuntimeError("Master File Size " + std::to_string(strlen(message)) +
" is greater than max str size " + std::to_string(MAX_MASTER_FILE_LENGTH));
}
if (fwrite((void*)message, 1, strlen(message), fd) != strlen(message))
return 1;
if (fwrite((void*)message, 1, strlen(message), fd) != strlen(message)) {
throw sls::RuntimeError("Master binary file incorrect number of bytes written to file");
}
BinaryFileStatic::CloseDataFile(fd);
return 0;
}
@ -203,22 +199,19 @@ class BinaryFileStatic {
* @param filebuffersize file buffer size
* @returns 0 for success and 1 for fail
*/
static int CreateDataFile(FILE*& fd, bool owenable, std::string fname, size_t filebuffersize)
static void CreateDataFile(FILE*& fd, bool owenable, std::string fname, size_t filebuffersize)
{
if(!owenable){
if (NULL == (fd = fopen((const char *) fname.c_str(), "wx"))){
FILE_LOG(logERROR) << "Could not create/overwrite file" << fname;
fd = 0;
return 1;
throw sls::RuntimeError("Could not create/overwrite file " + fname);
}
}else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){
FILE_LOG(logERROR) << "Could not create file" << fname;
} else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){
fd = 0;
return 1;
throw sls::RuntimeError("Could not create file " + fname);
}
//setting file buffer size to 16mb
setvbuf(fd,NULL,_IOFBF,filebuffersize);
return 0;
}
};

View File

@ -6,7 +6,8 @@
class MySocketTCP;
class ServerInterface;
#include <atomic>
#include <future>
class ClientInterface : private virtual slsDetectorDefs {
private:
@ -38,17 +39,16 @@ class ClientInterface : private virtual slsDetectorDefs {
void *arg);
private:
void startTCPSocket();
void stopTCPSocket();
static void *startTCPServerThread(void *this_pointer);
void startTCPServer();
int function_table();
int decode_function(sls::ServerInterface2 &socket);
int functionTable();
int decodeFunction(sls::ServerInterface2 &socket);
void functionNotImplemented();
void modeNotImplemented(const std::string& modename, int mode);
template <typename T>
void validate(T arg, T retval, std::string modename, numberMode hex);
void verifyLock();
void verifyIdle(sls::ServerInterface2 &socket);
int exec_command(sls::ServerInterface2 &socket);
int exit_server(sls::ServerInterface2 &socket);
@ -118,6 +118,17 @@ class ClientInterface : private virtual slsDetectorDefs {
int set_udp_port(sls::ServerInterface2 &socket);
int set_udp_port2(sls::ServerInterface2 &socket);
int set_num_interfaces(sls::ServerInterface2 &socket);
int set_adc_mask_10g(sls::ServerInterface2 &socket);
int set_num_counters(sls::ServerInterface2 &socket);
Implementation *impl() {
if (receiver != nullptr) {
return receiver.get();
} else {
throw sls::SocketError(
"Receiver not set up. Please use rx_hostname first.\n");
}
}
detectorType myDetectorType;
std::unique_ptr<Implementation> receiver{nullptr};
@ -125,14 +136,12 @@ class ClientInterface : private virtual slsDetectorDefs {
sls::ServerInterface2 &socket);
int ret{OK};
int fnum{-1};
/** Lock Status if server locked to a client */
int lockStatus{0};
int lockedByClient{0};
int portNumber{0};
std::atomic<bool> killTcpThread{false};
std::unique_ptr<std::thread> tcpThread;
int killTCPServerThread{0};
pthread_t TCPServer_thread;
bool tcpThreadCreated{false};
int portNumber;
//***callback parameters***
@ -148,17 +157,4 @@ class ClientInterface : private virtual slsDetectorDefs {
protected:
std::unique_ptr<sls::ServerSocket> server{nullptr};
private:
void VerifyLock();
void VerifyIdle(sls::ServerInterface2 &socket);
Implementation *impl() {
if (receiver != nullptr) {
return receiver.get();
} else {
throw sls::SocketError(
"Receiver not set up. Please use rx_hostname first.\n");
}
}
};

View File

@ -118,13 +118,6 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject {
*/
void SetGeneralData(GeneralData* g);
/**
* Set thread priority
* @priority priority
* @returns OK or FAIL
*/
int SetThreadPriority(int priority);
/**
* Set File Format
* @param f file format
@ -155,9 +148,8 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject {
/**
* Create New File
* @param attr master file attributes
* @returns OK or FAIL
*/
int CreateNewFile(masterAttributes& attr);
void CreateNewFile(masterAttributes& attr);
/**
* Closes files
@ -201,24 +193,12 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject {
private:
/**
* Get Type
* @return type
*/
std::string GetType() override;
/**
* Record First Index
* @param fnum frame index to record
*/
void RecordFirstIndex(uint64_t fnum);
/**
* Destroy file writer object
* @return OK or FAIL
*/
void DestroyFileWriter();
/**
* Thread Exeution for DataProcessor Class
* Pop bound addresses, process them,

View File

@ -79,13 +79,6 @@ class DataStreamer : private virtual slsDetectorDefs, public ThreadObject {
*/
void SetGeneralData(GeneralData* g);
/**
* Set thread priority
* @priority priority
* @returns OK or FAIL
*/
int SetThreadPriority(int priority);
/**
* Set number of detectors
* @param number of detectors in both dimensions
@ -114,19 +107,12 @@ class DataStreamer : private virtual slsDetectorDefs, public ThreadObject {
/**
* Restream stop dummy packet
* @return OK or FAIL
*/
int RestreamStop();
void RestreamStop();
private:
/**
* Get Type
* @return type
*/
std::string GetType();
/**
* Record First Index
* @param fnum frame index to record

View File

@ -78,9 +78,8 @@ class Fifo : private virtual slsDetectorDefs {
/**
* Create Fifos, allocate memory & push addresses into fifo
* @param fifoItemSize size of each fifo item
* @return OK if successful, else FAIL
*/
int CreateFifos(uint32_t fifoItemSize);
void CreateFifos(uint32_t fifoItemSize);
/**
* Destroy Fifos and deallocate memory

View File

@ -84,9 +84,8 @@ class File : private virtual slsDetectorDefs {
/**
* Create file
* @returns OK or FAIL
*/
virtual int CreateFile() = 0;
virtual void CreateFile() = 0;
/**
* Close Current File
@ -103,17 +102,15 @@ class File : private virtual slsDetectorDefs {
* @param buffer buffer to write from
* @param fnum current image number
* @param nump number of packets caught
* @param OK or FAIL
*/
virtual int WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) = 0;
virtual void WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) = 0;
/**
* Create master file
* @param mfwenable master file write enable
* @param attr master file attributes
* @returns OK or FAIL
*/
virtual int CreateMasterFile(bool mfwenable, masterAttributes& attr) = 0;
virtual void CreateMasterFile(bool mfwenable, masterAttributes& attr) = 0;
// HDf5 specific
/**

View File

@ -208,12 +208,21 @@ public:
/**
* set number of interfaces (jungfrau)
* @param number of interfaces
* @param n number of interfaces
*/
virtual void SetNumberofInterfaces(const int n) {
FILE_LOG(logERROR) << "SetNumberofInterfaces is a generic function that should be overloaded by a derived class";
}
/**
* set number of counters (mythen3)
* @param n number of counters
* @param dr dynamic range
*/
virtual void SetNumberofCounters(const int n, const int dr) {
FILE_LOG(logERROR) << "SetNumberofCounters is a generic function that should be overloaded by a derived class";
}
/**
* Print all variables
*/
@ -528,16 +537,19 @@ class JungfrauData : public GeneralData {
};
class Mythen3Data : public GeneralData {
public:
private:
int ncounters;
const int NCHAN = 1280;
public:
/** Constructor */
Mythen3Data(){
myDetectorType = slsDetectorDefs::MYTHEN3;
nPixelsX = (1280 * 3); // 1280 channels, 3 counters
ncounters = 3;
nPixelsX = (NCHAN * ncounters); // max 1280 channels x 3 counters
nPixelsY = 1;
headerSizeinPacket = sizeof(slsDetectorDefs::sls_detector_header);
dataSize = 7680;//8192;
dataSize = 7680;
packetSize = headerSizeinPacket + dataSize;
packetsPerFrame = 2;
imageSize = dataSize * packetsPerFrame;
@ -547,6 +559,42 @@ class Mythen3Data : public GeneralData {
standardheader = true;
defaultUdpSocketBufferSize = (1000 * 1024 * 1024);
};
/**
* set number of counters (mythen3)
* @param n number of counters
* @param dr dynamic range
*/
virtual void SetNumberofCounters(const int n, const int dr) {
if (n < 1 || n > 3) {
throw sls::RuntimeError("Invalid number of counters " + std::to_string(n));
}
ncounters = n;
nPixelsX = NCHAN * ncounters;
FILE_LOG(logINFO) << "nPixelsX: " << nPixelsX;
imageSize = nPixelsX * nPixelsY * ((dr > 16) ? 4 : // 32 bit
((dr > 8) ? 2 : // 16 bit
((dr > 4) ? 0.5 : // 4 bit
0.125))); // 1 bit
dataSize = imageSize / packetsPerFrame;
packetSize = headerSizeinPacket + dataSize;
FILE_LOG(logINFO) << "PacketSize: " << packetSize;
}
/**
* Setting dynamic range changes member variables
* @param dr dynamic range
* @param tgEnable (discarded, of no value to mythen3)
*/
void SetDynamicRange(int dr, bool tgEnable) {
imageSize = nPixelsX * nPixelsY * ((dr > 16) ? 4 : // 32 bit
((dr > 8) ? 2 : // 16 bit
((dr > 4) ? 0.5 : // 4 bit
0.125))); // 1 bit
dataSize = imageSize / packetsPerFrame;
packetSize = headerSizeinPacket + dataSize;
FILE_LOG(logINFO) << "PacketSize: " << packetSize;
}
};
@ -632,20 +680,21 @@ public:
nPixelsY = 1;
// 10G
if (t) {
/*
headerSizeinPacket = sizeof(slsDetectorDefs::sls_detector_header);
dataSize = UDP_PACKET_DATA_BYTES;
dataSize = 8144;
packetSize = headerSizeinPacket + dataSize;
imageSize = adatabytes + ddatabytes;
packetsPerFrame = ceil((double)imageSize / (double)dataSize);
standardheader = true;
*/
/*
headerSizeinPacket = 22;
dataSize = 8192;
packetSize = headerSizeinPacket + dataSize;
imageSize = adatabytes + ddatabytes;
packetsPerFrame = ceil((double)imageSize / (double)dataSize);
standardheader = false;
*/
}
// 1g udp (via fifo readout)
else {

View File

@ -17,6 +17,7 @@
#ifndef H5_NO_NAMESPACE
using namespace H5;
#endif
#include <mutex>
class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileStatic {
@ -67,9 +68,8 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
/**
* Create file
* @param fnum current frame index to include in file name
* @returns OK or FAIL
*/
int CreateFile();
void CreateFile();
/**
* Close Current File
@ -87,17 +87,15 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
* @param bsize size of buffer (not used)
* @param fnum current image number
* @param nump number of packets caught
* @returns OK or FAIL
*/
int WriteToFile(char* buffer, int bsize, uint64_t fnum, uint32_t nump);
void WriteToFile(char* buffer, int bsize, uint64_t fnum, uint32_t nump);
/**
* Create master file
* @param mfwenable master file write enable
* @param attr master file attributes
* @returns OK or FAIL
*/
int CreateMasterFile(bool mfwenable, masterAttributes& attr);
void CreateMasterFile(bool mfwenable, masterAttributes& attr);
/**
* End of Acquisition
@ -112,16 +110,14 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
/**
* Create Virtual File
* @param numf number of images caught
* @returns OK or FAIL
*/
int CreateVirtualFile(uint64_t numf);
void CreateVirtualFile(uint64_t numf);
/**
* Link virtual file in master file
* Only for Jungfrau at the moment for 1 module and 1 data file
* @returns OK or FAIL
*/
int LinkVirtualFileinMasterFile();
void LinkVirtualFileinMasterFile();
/**
* Get Type
@ -135,9 +131,8 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
void UpdateDataType();
/** mutex to update static items among objects (threads)*/
static pthread_mutex_t Mutex;
static mutable std::mutex mutex;
/** Master File handle */
static H5File* masterfd;

View File

@ -156,9 +156,8 @@ public:
* @param dspace dataspace pointer
* @param dset dataset pointer
* @param dtype datatype
* @returns 0 for success and 1 for fail
*/
static int WriteDataFile(int ind, char* buf,
static void WriteDataFile(int ind, char* buf,
uint64_t nDimx, uint32_t nDimy, uint32_t nDimz,
DataSpace* dspace, DataSet* dset, DataType dtype)
{
@ -176,9 +175,8 @@ public:
catch(const Exception& error){
FILE_LOG(logERROR) << "Could not write to file in object " << ind;
error.printErrorStack();
return 1;
throw RuntimeError("Could not write to file in object " + std::to_string(ind));
}
return 0;
}
@ -192,7 +190,7 @@ public:
* @param rheader sls_receiver_header pointer
* @param parameterDataTypes parameter datatypes
*/
static int WriteParameterDatasets(int ind, DataSpace* dspace_para, uint64_t fnum,
static void WriteParameterDatasets(int ind, DataSpace* dspace_para, uint64_t fnum,
std::vector <DataSet*> dset_para,sls_receiver_header* rheader,
std::vector <DataType> parameterDataTypes)
{
@ -236,11 +234,9 @@ public:
}i=14;
}
catch(const Exception& error){
FILE_LOG(logERROR) << "Could not write parameters (index:" << i << ") to file in object " << ind;
error.printErrorStack();
return 1;
throw RuntimeError("Could not write parameters (index:" + std::to_string(i) + ") to file in object " + std::to_string(ind));
}
return 0;
}
@ -253,9 +249,8 @@ public:
* @param dspace_para parameter dataspace address pointer
* @param dset dataset parameter pointer
* @param initialNumImages initial number of images
* @returns 0 for success and 1 for fail
*/
static int ExtendDataset(int ind, DataSpace*& dspace, DataSet* dset,
static void ExtendDataset(int ind, DataSpace*& dspace, DataSet* dset,
DataSpace*& dspace_para, std::vector <DataSet*> dset_para,
uint64_t initialNumImages) {
try{
@ -279,11 +274,9 @@ public:
}
catch(const Exception& error){
FILE_LOG(logERROR) << "Could not extend dataset in object " << ind;
error.printErrorStack();
return 1;
throw RuntimeError("Could not extend dataset in object " + std::to_string(ind));
}
return 0;
}
@ -292,9 +285,8 @@ public:
* @param fname master file name
* @param owenable overwrite enable
* @param attr master file attributes
* @returns 0 for success and 1 for fail
*/
static int CreateMasterDataFile(H5File*& fd, std::string fname, bool owenable,
static void CreateMasterDataFile(H5File*& fd, std::string fname, bool owenable,
masterAttributes& attr)
{
try {
@ -443,12 +435,10 @@ public:
fd->close();
} catch(const Exception& error) {
FILE_LOG(logERROR) << "Could not create master HDF5 handles";
error.printErrorStack();
if (fd) fd->close();
return 1;
throw RuntimeError("Could not create master HDF5 handles");
}
return 0;
}
@ -473,9 +463,8 @@ public:
* @param dset_para vector of datasets of parameters
* @param parameterNames parameter names
* @param parameterDataTypes parameter datatypes
* @returns 0 for success and 1 for fail
*/
static int CreateDataFile(int ind, bool owenable, std::string fname, bool frindexenable,
static void CreateDataFile(int ind, bool owenable, std::string fname, bool frindexenable,
uint64_t fnum, uint64_t nDimx, uint32_t nDimy, uint32_t nDimz,
DataType dtype, H5File*& fd, DataSpace*& dspace, DataSet*& dset,
double version, uint64_t maxchunkedimages,
@ -547,12 +536,10 @@ public:
}
}
catch(const Exception& error){
FILE_LOG(logERROR) << "Could not create HDF5 handles in object " << ind;
error.printErrorStack();
if (fd) fd->close();
return 1;
throw RuntimeError("Could not create HDF5 handles in object " + ind);
}
return 0;
}
@ -579,9 +566,8 @@ public:
* @param version version of software for hdf5 writing
* @param parameterNames parameter names
* @param parameterDataTypes parameter datatypes
* @returns 0 for success and 1 for fail
*/
static int CreateVirtualDataFile(
static void CreateVirtualDataFile(
std::string virtualFileName,
hid_t& fd, std::string masterFileName,
std::string fpath, std::string fnameprefix, uint64_t findex, bool frindexenable,
@ -593,206 +579,167 @@ public:
std::vector <const char*> parameterNames,
std::vector <DataType> parameterDataTypes)
{
//file
hid_t dfal = H5Pcreate (H5P_FILE_ACCESS);
if (dfal < 0)
return CloseFileOnError(fd,
std::string("Could not create file access property for virtual file ")
+ virtualFileName + std::string("\n"));
if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0)
return CloseFileOnError(fd,
std::string("Could not set strong file close degree for virtual file ")
+ virtualFileName + std::string("\n"));
fd = H5Fcreate( virtualFileName.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, dfal);
if (fd < 0)
return CloseFileOnError(fd,
std::string("Could not create virtual file ") + virtualFileName + std::string("\n"));
try {
//file
hid_t dfal = H5Pcreate (H5P_FILE_ACCESS);
if (dfal < 0)
throw RuntimeError("Could not create file access property for virtual file " + virtualFileName);
if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0)
throw RuntimeError("Could not set strong file close degree for virtual file " + virtualFileName);
fd = H5Fcreate( virtualFileName.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, dfal);
if (fd < 0)
throw RuntimeError("Could not create virtual file " + virtualFileName);
//attributes - version
hid_t dataspace_attr = H5Screate (H5S_SCALAR);
if (dataspace_attr < 0)
return CloseFileOnError(fd,
std::string("Could not create dataspace for attribute in virtual file ")
+ virtualFileName + std::string("\n"));
hid_t attrid = H5Acreate2 (fd, "version", H5T_NATIVE_DOUBLE, dataspace_attr, H5P_DEFAULT, H5P_DEFAULT);
if (attrid < 0)
return CloseFileOnError(fd,
std::string("Could not create attribute in virtual file ")
+ virtualFileName + std::string("\n"));
double attr_data = version;
if (H5Awrite (attrid, H5T_NATIVE_DOUBLE, &attr_data) < 0)
return CloseFileOnError(fd,
std::string("Could not write attribute in virtual file ")
+ virtualFileName + std::string("\n"));
if (H5Aclose (attrid) < 0)
return CloseFileOnError(fd,
std::string("Could not close attribute in virtual file ")
+ virtualFileName + std::string("\n"));
//attributes - version
hid_t dataspace_attr = H5Screate (H5S_SCALAR);
if (dataspace_attr < 0)
throw RuntimeError("Could not create dataspace for attribute in virtual file " + virtualFileName);
hid_t attrid = H5Acreate2 (fd, "version", H5T_NATIVE_DOUBLE, dataspace_attr, H5P_DEFAULT, H5P_DEFAULT);
if (attrid < 0)
throw RuntimeError("Could not create attribute in virtual file " + virtualFileName);
double attr_data = version;
if (H5Awrite (attrid, H5T_NATIVE_DOUBLE, &attr_data) < 0)
throw RuntimeError("Could not write attribute in virtual file " + virtualFileName);
if (H5Aclose (attrid) < 0)
throw RuntimeError("Could not close attribute in virtual file " + virtualFileName);
//virtual dataspace
hsize_t vdsdims[3] = {numf, numDety * nDimy, numDetz * nDimz};
hid_t vdsDataspace = H5Screate_simple(3, vdsdims ,NULL);
if (vdsDataspace < 0)
return CloseFileOnError(fd,
std::string("Could not create virtual dataspace in virtual file ")
+ virtualFileName + std::string("\n"));
hsize_t vdsdims_para[2] = {numf, (unsigned int) numDety * numDetz};
hid_t vdsDataspace_para = H5Screate_simple(2, vdsdims_para, NULL);
if (vdsDataspace_para < 0)
return CloseFileOnError(fd,
std::string("Could not create virtual dataspace (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
//virtual dataspace
hsize_t vdsdims[3] = {numf, numDety * nDimy, numDetz * nDimz};
hid_t vdsDataspace = H5Screate_simple(3, vdsdims ,NULL);
if (vdsDataspace < 0)
throw RuntimeError("Could not create virtual dataspace in virtual file " + virtualFileName);
hsize_t vdsdims_para[2] = {numf, (unsigned int) numDety * numDetz};
hid_t vdsDataspace_para = H5Screate_simple(2, vdsdims_para, NULL);
if (vdsDataspace_para < 0)
throw RuntimeError("Could not create virtual dataspace (parameters) in virtual file " + virtualFileName);
//fill values
hid_t dcpl = H5Pcreate (H5P_DATASET_CREATE);
if (dcpl < 0)
return CloseFileOnError(fd,
std::string("Could not create file creation properties in virtual file ")
+ virtualFileName + std::string("\n"));
int fill_value = -1;
if (H5Pset_fill_value (dcpl, GetDataTypeinC(dataType), &fill_value) < 0)
return CloseFileOnError(fd,
std::string("Could not create fill value in virtual file ")
+ virtualFileName + std::string("\n"));
hid_t dcpl_para[parameterNames.size()];
for (unsigned int i = 0; i < parameterNames.size(); ++i) {
dcpl_para[i] = H5Pcreate (H5P_DATASET_CREATE);
if (dcpl_para[i] < 0)
return CloseFileOnError(fd,
std::string("Could not create file creation properties (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
if (H5Pset_fill_value (dcpl_para[i], GetDataTypeinC(parameterDataTypes[i]), &fill_value) < 0)
return CloseFileOnError(fd,
std::string("Could not create fill value (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
}
//hyperslab
int numMajorHyperslab = numf/maxFramesPerFile;
if (numf%maxFramesPerFile) numMajorHyperslab++;
bool error = false;
uint64_t framesSaved = 0;
for (int j = 0; j < numMajorHyperslab; j++) {
uint64_t nDimx = ((numf - framesSaved) > maxFramesPerFile)
? maxFramesPerFile : (numf-framesSaved);
hsize_t offset[3] = {framesSaved, 0, 0};
hsize_t count[3] = {nDimx, nDimy, nDimz};
hsize_t offset_para[2] = {framesSaved, 0};
hsize_t count_para[2] = {nDimx, 1};
for (int i = 0; i < numDety * numDetz; ++i) {
//setect hyperslabs
if (H5Sselect_hyperslab (vdsDataspace, H5S_SELECT_SET, offset, NULL, count, NULL) < 0) {
FILE_LOG(logERROR) << "Could not select hyperslab";
error = true;
break;
}
if (H5Sselect_hyperslab (vdsDataspace_para, H5S_SELECT_SET,
offset_para, NULL, count_para, NULL) < 0) {
FILE_LOG(logERROR) << "Could not select hyperslab for parameters";
error = true;
break;
}
//source file name
std::string srcFileName = HDF5FileStatic::CreateFileName(fpath, fnameprefix, findex,
j, dindex, numunits, i);
FILE_LOG(logERROR) << srcFileName;
// find relative path
std::string relative_srcFileName = srcFileName;
{
size_t i = srcFileName.rfind('/', srcFileName.length());
if (i != std::string::npos)
relative_srcFileName = (srcFileName.substr(i+1, srcFileName.length() - i));
}
//source dataset name
std::ostringstream osfn;
osfn << "/data";
if (frindexenable) osfn << "_f" << std::setfill('0') << std::setw(12) << j;
std::string srcDatasetName = osfn.str();
//source dataspace
hsize_t srcdims[3] = {nDimx, nDimy, nDimz};
hsize_t srcdimsmax[3] = {H5S_UNLIMITED, nDimy, nDimz};
hid_t srcDataspace = H5Screate_simple(3, srcdims, srcdimsmax);
if (srcDataspace < 0)
return CloseFileOnError(fd,
std::string("Could not create source dataspace in virtual file ")
+ virtualFileName + std::string("\n"));
hsize_t srcdims_para[1] = {nDimx};
hsize_t srcdimsmax_para[1] = {H5S_UNLIMITED};
hid_t srcDataspace_para = H5Screate_simple(1, srcdims_para, srcdimsmax_para);
if (srcDataspace_para < 0)
return CloseFileOnError(fd,
std::string("Could not create source dataspace (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
//mapping
if (H5Pset_virtual(dcpl, vdsDataspace, relative_srcFileName.c_str(),
srcDatasetName.c_str(), srcDataspace) < 0) {
FILE_LOG(logERROR) << "Could not set mapping for paramter 1";
error = true;
break;
}
for (unsigned int k = 0; k < parameterNames.size(); ++k) {
if (H5Pset_virtual(dcpl_para[k], vdsDataspace_para, relative_srcFileName.c_str(),
parameterNames[k], srcDataspace_para) < 0) {
FILE_LOG(logERROR) << "Could not set mapping for paramter " << k;
error = true;
break;
}
}
//H5Sclose(srcDataspace);
//H5Sclose(srcDataspace_para);
offset[2] += nDimz;
if (offset[2] >= (numDetz * nDimz)) {
offset[2] = 0;
offset[1] += nDimy;
}
offset_para[1]++;
//fill values
hid_t dcpl = H5Pcreate (H5P_DATASET_CREATE);
if (dcpl < 0)
throw RuntimeError("Could not create file creation properties in virtual file " + virtualFileName);
int fill_value = -1;
if (H5Pset_fill_value (dcpl, GetDataTypeinC(dataType), &fill_value) < 0)
throw RuntimeError("Could not create fill value in virtual file " + virtualFileName);
hid_t dcpl_para[parameterNames.size()];
for (unsigned int i = 0; i < parameterNames.size(); ++i) {
dcpl_para[i] = H5Pcreate (H5P_DATASET_CREATE);
if (dcpl_para[i] < 0)
throw RuntimeError("Could not create file creation properties (parameters) in virtual file " + virtualFileName);
if (H5Pset_fill_value (dcpl_para[i], GetDataTypeinC(parameterDataTypes[i]), &fill_value) < 0)
throw RuntimeError("Could not create fill value (parameters) in virtual file " + virtualFileName);
}
framesSaved += nDimx;
//hyperslab
int numMajorHyperslab = numf/maxFramesPerFile;
if (numf%maxFramesPerFile) numMajorHyperslab++;
uint64_t framesSaved = 0;
for (int j = 0; j < numMajorHyperslab; j++) {
uint64_t nDimx = ((numf - framesSaved) > maxFramesPerFile)
? maxFramesPerFile : (numf-framesSaved);
hsize_t offset[3] = {framesSaved, 0, 0};
hsize_t count[3] = {nDimx, nDimy, nDimz};
hsize_t offset_para[2] = {framesSaved, 0};
hsize_t count_para[2] = {nDimx, 1};
for (int i = 0; i < numDety * numDetz; ++i) {
//setect hyperslabs
if (H5Sselect_hyperslab (vdsDataspace, H5S_SELECT_SET, offset, NULL, count, NULL) < 0) {
throw RuntimeError("Could not select hyperslab");
}
if (H5Sselect_hyperslab (vdsDataspace_para, H5S_SELECT_SET,
offset_para, NULL, count_para, NULL) < 0) {
throw RuntimeError("Could not select hyperslab for parameters");
}
//source file name
std::string srcFileName = HDF5FileStatic::CreateFileName(fpath, fnameprefix, findex,
j, dindex, numunits, i);
FILE_LOG(logERROR) << srcFileName;
// find relative path
std::string relative_srcFileName = srcFileName;
{
size_t i = srcFileName.rfind('/', srcFileName.length());
if (i != std::string::npos)
relative_srcFileName = (srcFileName.substr(i+1, srcFileName.length() - i));
}
//source dataset name
std::ostringstream osfn;
osfn << "/data";
if (frindexenable) osfn << "_f" << std::setfill('0') << std::setw(12) << j;
std::string srcDatasetName = osfn.str();
//source dataspace
hsize_t srcdims[3] = {nDimx, nDimy, nDimz};
hsize_t srcdimsmax[3] = {H5S_UNLIMITED, nDimy, nDimz};
hid_t srcDataspace = H5Screate_simple(3, srcdims, srcdimsmax);
if (srcDataspace < 0)
throw RuntimeError("Could not create source dataspace in virtual file " + virtualFileName);
hsize_t srcdims_para[1] = {nDimx};
hsize_t srcdimsmax_para[1] = {H5S_UNLIMITED};
hid_t srcDataspace_para = H5Screate_simple(1, srcdims_para, srcdimsmax_para);
if (srcDataspace_para < 0)
throw RuntimeError("Could not create source dataspace (parameters) in virtual file " + virtualFileName);
//mapping
if (H5Pset_virtual(dcpl, vdsDataspace, relative_srcFileName.c_str(),
srcDatasetName.c_str(), srcDataspace) < 0) {
throw RuntimeError("Could not set mapping for paramter 1");
}
for (unsigned int k = 0; k < parameterNames.size(); ++k) {
if (H5Pset_virtual(dcpl_para[k], vdsDataspace_para, relative_srcFileName.c_str(),
parameterNames[k], srcDataspace_para) < 0) {
throw RuntimeError("Could not set mapping for paramter " + std::to_string(k));
}
}
//H5Sclose(srcDataspace);
//H5Sclose(srcDataspace_para);
offset[2] += nDimz;
if (offset[2] >= (numDetz * nDimz)) {
offset[2] = 0;
offset[1] += nDimy;
}
offset_para[1]++;
}
framesSaved += nDimx;
}
//dataset
std::string virtualDatasetName = srcDataseName;
hid_t vdsdataset = H5Dcreate2 (fd, virtualDatasetName.c_str(),
GetDataTypeinC(dataType), vdsDataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT);
if (vdsdataset < 0)
throw RuntimeError("Could not create virutal dataset in virtual file " + virtualFileName);
//virtual parameter dataset
for (unsigned int i = 0; i < parameterNames.size(); ++i) {
hid_t vdsdataset_para = H5Dcreate2 (fd,
parameterNames[i],
GetDataTypeinC(parameterDataTypes[i]), vdsDataspace_para,
H5P_DEFAULT, dcpl_para[i], H5P_DEFAULT);
if (vdsdataset_para < 0)
throw RuntimeError("Could not create virutal dataset (parameters) in virtual file " + virtualFileName);
}
//close
H5Fclose(fd);
fd = 0;
//link
LinkVirtualInMaster(masterFileName, virtualFileName, virtualDatasetName, parameterNames);
} catch (const RuntimeError &e) {
if (fd > 0)
H5Fclose(fd);
fd = 0;
}
if (error)
return CloseFileOnError(fd,
std::string("Could not map files in virtual file ")
+ virtualFileName + std::string("\n"));
//dataset
std::string virtualDatasetName = srcDataseName;
hid_t vdsdataset = H5Dcreate2 (fd, virtualDatasetName.c_str(),
GetDataTypeinC(dataType), vdsDataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT);
if (vdsdataset < 0)
return CloseFileOnError(fd,
std::string("Could not create virutal dataset in virtual file ")
+ virtualFileName + std::string("\n"));
//virtual parameter dataset
for (unsigned int i = 0; i < parameterNames.size(); ++i) {
hid_t vdsdataset_para = H5Dcreate2 (fd,
parameterNames[i],
GetDataTypeinC(parameterDataTypes[i]), vdsDataspace_para,
H5P_DEFAULT, dcpl_para[i], H5P_DEFAULT);
if (vdsdataset_para < 0)
return CloseFileOnError(fd,
std::string("Could not create virutal dataset (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
}
//close
H5Fclose(fd); fd = 0;
//link
return LinkVirtualInMaster(masterFileName, virtualFileName, virtualDatasetName, parameterNames);
}
@ -809,10 +756,9 @@ public:
* @param nDimx Number of objects in x dimension
* @param nDimy Number of objects in y dimension
* @param nDimz Number of objects in z dimension
* @returns 0 for success and 1 for fail
*/
template <typename T>
static int CopyVirtualFile(T datatype, bool owenable, std::string oldFileName, std::string oldDatasetName,
static void CopyVirtualFile(T datatype, bool owenable, std::string oldFileName, std::string oldDatasetName,
std::string newFileName, std::string newDatasetName, int rank,
uint64_t nDimx, uint32_t nDimy, uint32_t nDimz=0)
{
@ -825,8 +771,7 @@ public:
data_out = (T*)malloc(sizeof(T)*(nDimx*nDimy*nDimz));
break;
default:
FILE_LOG(logERROR) << "Invalid rank. Options: 2 or 3";
return 0;
throw RuntimeError("Invalid rank. Options: 2 or 3");
}
if (datatype == PredType::STD_U16LE) {
FILE_LOG(logINFO) << "datatype:16";
@ -837,8 +782,7 @@ public:
} else if (datatype == PredType::STD_U8LE) {
FILE_LOG(logINFO) << "datatype:8";
} else {
FILE_LOG(logERROR) << "Unknown datatype: " << datatype;
return 1;
throw RuntimeError("Unknown datatype:" + std::to_string(datatype));
}
FILE_LOG(logINFO) << "owenable:" << (owenable?1:0) << std::endl
<< "oldFileName:" << oldFileName << std::endl
@ -888,15 +832,13 @@ public:
newfd->close();
oldfd->close();
} catch(const Exception& error){
FILE_LOG(logERROR) << "Could not copy virtual files";
error.printErrorStack();
free(data_out);
oldfd->close();
newfd->close();
return 1;
throw RuntimeError("Could not copy virtual files");
}
free(data_out);
return 0;
}
@ -908,89 +850,80 @@ public:
* @param virtualfname virtual file name
* @param virtualDatasetname virtual dataset name
* @param parameterNames parameter names
* @returns 0 for success and 1 for fail
*/
static int LinkVirtualInMaster(std::string masterFileName, std::string virtualfname,
static void LinkVirtualInMaster(std::string masterFileName, std::string virtualfname,
std::string virtualDatasetname, std::vector <const char*> parameterNames) {
char linkname[100];
hid_t vfd = 0;
hid_t dfal = H5Pcreate (H5P_FILE_ACCESS);
if (dfal < 0)
return CloseFileOnError( vfd, std::string("Could not create file access property for link\n"));
if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0)
return CloseFileOnError( vfd, std::string("Could not set strong file close degree for link\n"));
try {
hid_t dfal = H5Pcreate (H5P_FILE_ACCESS);
if (dfal < 0)
throw RuntimeError("Could not create file access property for link");
if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0)
throw RuntimeError("Could not set strong file close degree for link");
//open master file
hid_t mfd = H5Fopen( masterFileName.c_str(), H5F_ACC_RDWR, dfal);
if (mfd < 0)
return CloseFileOnError( vfd, std::string("Could not open master file\n"));
//open master file
hid_t mfd = H5Fopen( masterFileName.c_str(), H5F_ACC_RDWR, dfal);
if (mfd < 0)
throw RuntimeError("Could not open master file");
//open virtual file
vfd = H5Fopen( virtualfname.c_str(), H5F_ACC_RDWR, dfal);
if (vfd < 0) {
H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not open virtual file\n"));
}
// find relative path
std::string relative_virtualfname = virtualfname;
{
size_t i = virtualfname.rfind('/', virtualfname.length());
if (i != std::string::npos)
relative_virtualfname = (virtualfname.substr(i+1, virtualfname.length() - i));
}
//**data dataset**
hid_t vdset = H5Dopen2( vfd, virtualDatasetname.c_str(), H5P_DEFAULT);
if (vdset < 0) {
H5Fclose(mfd);
return CloseFileOnError( vfd, std::string("Could not open virtual data dataset\n"));
}
sprintf(linkname, "/entry/data/%s",virtualDatasetname.c_str());
if(H5Lcreate_external( relative_virtualfname.c_str(), virtualDatasetname.c_str(),
mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) {
H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not create link to data dataset\n"));
}
H5Dclose(vdset);
//**paramter datasets**
for (unsigned int i = 0; i < parameterNames.size(); ++i){
hid_t vdset_para = H5Dopen2( vfd, (std::string (parameterNames[i])).c_str(), H5P_DEFAULT);
if (vdset_para < 0) {
//open virtual file
vfd = H5Fopen( virtualfname.c_str(), H5F_ACC_RDWR, dfal);
if (vfd < 0) {
H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not open virtual parameter dataset to create link\n"));
throw RuntimeError("Could not open virtual file");
}
sprintf(linkname, "/entry/data/%s",(std::string (parameterNames[i])).c_str());
if(H5Lcreate_external( relative_virtualfname.c_str(), (std::string (parameterNames[i])).c_str(),
mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) {
// find relative path
std::string relative_virtualfname = virtualfname;
{
size_t i = virtualfname.rfind('/', virtualfname.length());
if (i != std::string::npos)
relative_virtualfname = (virtualfname.substr(i+1, virtualfname.length() - i));
}
//**data dataset**
hid_t vdset = H5Dopen2( vfd, virtualDatasetname.c_str(), H5P_DEFAULT);
if (vdset < 0) {
H5Fclose(mfd);
throw RuntimeError("Could not open virtual data dataset");
}
sprintf(linkname, "/entry/data/%s",virtualDatasetname.c_str());
if(H5Lcreate_external( relative_virtualfname.c_str(), virtualDatasetname.c_str(),
mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) {
H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not create link to virtual parameter dataset\n"));
throw RuntimeError("Could not create link to data dataset");
}
}
H5Dclose(vdset);
H5Fclose(mfd); mfd = 0;
H5Fclose(vfd); vfd = 0;
return 0;
//**paramter datasets**
for (unsigned int i = 0; i < parameterNames.size(); ++i){
hid_t vdset_para = H5Dopen2( vfd, (std::string (parameterNames[i])).c_str(), H5P_DEFAULT);
if (vdset_para < 0) {
H5Fclose(mfd); mfd = 0;
throw RuntimeError("Could not open virtual parameter dataset to create link");
}
sprintf(linkname, "/entry/data/%s",(std::string (parameterNames[i])).c_str());
if(H5Lcreate_external( relative_virtualfname.c_str(), (std::string (parameterNames[i])).c_str(),
mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) {
H5Fclose(mfd); mfd = 0;
throw RuntimeError("Could not create link to virtual parameter dataset");
}
}
H5Fclose(mfd); mfd = 0;
H5Fclose(vfd); vfd = 0;
} catch () {
if(vfd > 0)
H5Fclose(vfd);
vfd = 0;
}
}
/**
* Print Error msg and Close File and called on error
* @returns 1 for fail
*/
static int CloseFileOnError(hid_t& fd, const std::string msg) {
FILE_LOG(logERROR) << msg;
if(fd > 0)
H5Fclose(fd);
fd = 0;
return 1;
}
/**
* Get Data type in C
* @param dtype datatype in C++

View File

@ -17,22 +17,16 @@ class slsDetectorDefs;
class Implementation : private virtual slsDetectorDefs {
public:
Implementation();
Implementation(const detectorType d);
virtual ~Implementation();
/**************************************************
* *
* Configuration Parameters *
* *
* ************************************************/
/**
* Set receiver type. It is the first function called by the client when
* connecting to receiver
* @param d detector type
* @return OK or FAIL
*/
int setDetectorType(const detectorType d);
void setDetectorType(const detectorType d);
int *getMultiDetectorSize() const;
void setMultiDetectorSize(const int *size);
int getDetectorPositionId() const;
@ -42,7 +36,7 @@ class Implementation : private virtual slsDetectorDefs {
bool getSilentMode() const;
void setSilentMode(const bool i);
uint32_t getFifoDepth() const;
int setFifoDepth(const uint32_t i);
void setFifoDepth(const uint32_t i);
frameDiscardPolicy getFrameDiscardPolicy() const;
void setFrameDiscardPolicy(const frameDiscardPolicy i);
bool getFramePaddingEnable() const;
@ -81,13 +75,13 @@ class Implementation : private virtual slsDetectorDefs {
uint64_t getFramesCaught() const;
uint64_t getAcquisitionIndex() const;
std::vector<uint64_t> getNumMissingPackets() const;
int startReceiver(std::string& err);
void startReceiver();
void setStoppedFlag(bool stopped);
void stopReceiver();
void startReadout();
void shutDownUDPSockets();
void closeFiles();
int restreamStop();
void restreamStop();
/**************************************************
@ -97,7 +91,7 @@ class Implementation : private virtual slsDetectorDefs {
* ************************************************/
int getNumberofUDPInterfaces() const;
/* [Jungfrau] */
int setNumberofUDPInterfaces(const int n);
void setNumberofUDPInterfaces(const int n);
std::string getEthernetInterface() const;
void setEthernetInterface(const std::string &c);
std::string getEthernetInterface2() const;
@ -109,7 +103,7 @@ class Implementation : private virtual slsDetectorDefs {
/* [Eiger][Jungfrau] */
void setUDPPortNumber2(const uint32_t i);
int64_t getUDPSocketBufferSize() const;
int setUDPSocketBufferSize(const int64_t s);
void setUDPSocketBufferSize(const int64_t s);
int64_t getActualUDPSocketBufferSize() const;
@ -119,10 +113,10 @@ class Implementation : private virtual slsDetectorDefs {
* *
* ************************************************/
bool getDataStreamEnable() const;
int setDataStreamEnable(const bool enable);
void setDataStreamEnable(const bool enable);
uint32_t getStreamingFrequency() const;
/* 0 for timer */
int setStreamingFrequency(const uint32_t freq);
void setStreamingFrequency(const uint32_t freq);
uint32_t getStreamingTimer() const;
void setStreamingTimer(const uint32_t time_in_ms);
uint32_t getStreamingPort() const;
@ -151,26 +145,28 @@ class Implementation : private virtual slsDetectorDefs {
void setSubPeriod(const uint64_t i);
uint32_t getNumberofAnalogSamples() const;
/**[Ctb][Moench] */
int setNumberofAnalogSamples(const uint32_t i);
void setNumberofAnalogSamples(const uint32_t i);
uint32_t getNumberofDigitalSamples() const;
/**[Ctb] */
int setNumberofDigitalSamples(const uint32_t i);
void setNumberofDigitalSamples(const uint32_t i);
int getNumberofCounters() const;
void setNumberofCounters(const int i);
uint32_t getDynamicRange() const;
int setDynamicRange(const uint32_t i);
void setDynamicRange(const uint32_t i);
ROI getROI() const;
/* [Gotthard] */
int setROI(ROI arg);
void setROI(ROI arg);
bool getTenGigaEnable() const;
/* [Eiger][Ctb] */
int setTenGigaEnable(const bool b);
void setTenGigaEnable(const bool b);
int getFlippedDataX() const;
void setFlippedDataX(int enable = -1);
bool getGapPixelsEnable() const;
/* [Eiger] */
int setGapPixelsEnable(const bool b);
void setGapPixelsEnable(const bool b);
bool getQuad() const;
/* [Eiger] */
int setQuad(const bool b);
void setQuad(const bool b);
bool getActivate() const;
/** [Eiger] If deactivated, receiver will create dummy data if deactivated padding is enabled (as it will receive nothing from detector) */
bool setActivate(const bool enable);
@ -182,10 +178,13 @@ class Implementation : private virtual slsDetectorDefs {
void setReadNLines(const int value);
readoutMode getReadoutMode() const;
/* [Ctb] */
int setReadoutMode(const readoutMode f);
void setReadoutMode(const readoutMode f);
uint32_t getADCEnableMask() const;
/* [Ctb][Moench] */
int setADCEnableMask(const uint32_t mask);
void setADCEnableMask(const uint32_t mask);
uint32_t getTenGigaADCEnableMask() const;
/* [Ctb][Moench] */
void setTenGigaADCEnableMask(const uint32_t mask);
std::vector<int> getDbitList() const;
/* [Ctb] */
void setDbitList(const std::vector<int> v);
@ -212,11 +211,11 @@ class Implementation : private virtual slsDetectorDefs {
void InitializeMembers();
void SetLocalNetworkParameters();
void SetThreadPriorities();
int SetupFifoStructure();
void SetupFifoStructure();
void ResetParametersforNewAcquisition();
int CreateUDPSockets();
int SetupWriter();
void CreateUDPSockets();
void SetupWriter();
void StartRunning();
@ -274,6 +273,7 @@ class Implementation : private virtual slsDetectorDefs {
uint64_t subPeriod;
uint64_t numberOfAnalogSamples;
uint64_t numberOfDigitalSamples;
int numberOfCounters;
uint32_t dynamicRange;
ROI roi;
bool tengigaEnable;
@ -284,7 +284,8 @@ class Implementation : private virtual slsDetectorDefs {
bool deactivatedPaddingEnable;
int numLinesReadout;
readoutMode readoutType;
uint32_t adcEnableMask;
uint32_t adcEnableMaskOneGiga;
uint32_t adcEnableMaskTenGiga;
std::vector<int> ctbDbitList;
int ctbDbitOffset;
int ctbAnalogDataBytes;

View File

@ -102,18 +102,10 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject {
*/
void SetGeneralData(GeneralData* g);
/**
* Set thread priority
* @priority priority
* @returns OK or FAIL
*/
int SetThreadPriority(int priority);
/**
* Creates UDP Sockets
* @return OK or FAIL
*/
int CreateUDPSockets();
void CreateUDPSockets();
/**
* Shuts down and deletes UDP Sockets
@ -124,9 +116,8 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject {
* Create & closes a dummy UDP socket
* to set & get actual buffer size
* @param s UDP socket buffer size to be set
* @return OK or FAIL of dummy socket creation
*/
int CreateDummySocketForUDPSocketBufferSize(int64_t s);
void CreateDummySocketForUDPSocketBufferSize(int64_t s);
/**
* Set hard coded (calculated but not from detector) row and column
@ -139,12 +130,6 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject {
private:
/**
* Get Type
* @return type
*/
std::string GetType() override;
/**
* Record First Acquisition Index
* @param fnum frame index to record

View File

@ -10,77 +10,27 @@
#include "sls_detector_defs.h"
#include "logger.h"
#include <pthread.h>
#include <semaphore.h>
#include <string>
#include <atomic>
#include <future>
class ThreadObject : private virtual slsDetectorDefs {
public:
/**
* Constructor
* @param ind self index
*/
ThreadObject(int ind);
/**
* Destructor
* if alive, destroys thread
*/
ThreadObject(int threadIndex, std::string threadType);
virtual ~ThreadObject();
/**
* Print all member values
*/
void PrintMembers();
/**
* Get Type
* @return type
*/
virtual std::string GetType() = 0;
/**
* Returns if the thread is currently running
* @returns true if thread is running, else false
*/
virtual bool IsRunning() = 0;
/**
* What is really being executed in the thread
*/
virtual void ThreadExecution() = 0;
/**
* Post semaphore so thread can continue & start an acquisition
*/
void Continue();
void SetThreadPriority(int priority);
protected:
/**
* Destroy thread, semaphore and resets alive and killThread
*/
void DestroyThread();
/**
* Create Thread, sets semaphore, alive and killThread
* @return OK if successful, else FAIL
*/
int CreateThread();
virtual void ThreadExecution() = 0;
private:
/**
* Static function using pointer from argument to call RunningThread()
* @param thisPointer pointer to an object of ThreadObject
*/
static void* StartThread(void *thisPointer);
/**
* Actual Thread called: An infinite while loop in which,
* Thread called: An infinite while loop in which,
* semaphore starts executing its contents as long RunningMask is satisfied
* Then it exits the thread on its own if killThread is true
*/
@ -88,22 +38,10 @@ class ThreadObject : private virtual slsDetectorDefs {
protected:
/** Self Index */
int index;
/** Thread is alive/dead */
volatile bool alive;
/** Variable monitored by thread to kills itself */
volatile bool killThread;
/** Thread variable */
pthread_t thread;
/** Semaphore to synchonize starting of each run */
int index{0};
std::string type;
std::atomic<bool> killThread{false};
std::unique_ptr<std::thread> threadObject;
sem_t semaphore;
};

View File

@ -42,20 +42,18 @@ slsDetectorDefs::fileFormat BinaryFile::GetFileType() {
}
int BinaryFile::CreateFile() {
void BinaryFile::CreateFile() {
numFramesInFile = 0;
numActualPacketsInFile = 0;
currentFileName = BinaryFileStatic::CreateFileName(*filePath, *fileNamePrefix, *fileIndex,
subFileIndex, *detIndex, *numUnitsPerDetector, index);
if (BinaryFileStatic::CreateDataFile(filefd, *overWriteEnable, currentFileName, FILE_BUFFER_SIZE) == FAIL)
return FAIL;
BinaryFileStatic::CreateDataFile(filefd, *overWriteEnable, currentFileName, FILE_BUFFER_SIZE);
if(!(*silentMode)) {
FILE_LOG(logINFO) << "[" << *udpPortNumber << "]: Binary File created: " << currentFileName;
}
return OK;
}
void BinaryFile::CloseCurrentFile() {
@ -68,7 +66,7 @@ void BinaryFile::CloseAllFiles() {
BinaryFileStatic::CloseDataFile(masterfd);
}
int BinaryFile::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) {
void BinaryFile::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) {
// check if maxframesperfile = 0 for infinite
if ((*maxFramesPerFile) && (numFramesInFile >= (*maxFramesPerFile))) {
CloseCurrentFile();
@ -107,14 +105,12 @@ int BinaryFile::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_
// if write error
if (ret != buffersize) {
FILE_LOG(logERROR) << index << " Error: Write to file failed for image number " << fnum;
return FAIL;
throw sls::RuntimeError(std::to_string(index) + " : Write to file failed for image number " + std::to_string(fnum));
}
return OK;
}
int BinaryFile::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
void BinaryFile::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
//beginning of every acquisition
numFramesInFile = 0;
numActualPacketsInFile = 0;
@ -126,10 +122,9 @@ int BinaryFile::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
FILE_LOG(logINFO) << "Master File: " << masterFileName;
}
attr.version = BINARY_WRITER_VERSION;
return BinaryFileStatic::CreateMasterDataFile(masterfd, masterFileName,
BinaryFileStatic::CreateMasterDataFile(masterfd, masterFileName,
*overWriteEnable, attr);
}
return OK;
}

View File

@ -20,38 +20,24 @@ using sls::RuntimeError;
using sls::SocketError;
using Interface = sls::ServerInterface2;
ClientInterface::~ClientInterface() { stopTCPSocket(); }
ClientInterface::~ClientInterface() {
killTcpThread = true;
// shut down tcp sockets
if (server.get() != nullptr) {
FILE_LOG(logINFO) << "Shutting down TCP Socket on port " << portNumber;
server->shutDownSocket();
FILE_LOG(logDEBUG) << "TCP Socket closed on port " << portNumber;
}
// shut down tcp thread
tcpThread->join();
}
ClientInterface::ClientInterface(int portNumber)
: myDetectorType(GOTTHARD), portNumber(portNumber > 0 ? portNumber : DEFAULT_PORTNO + 2) {
function_table();
startTCPSocket();
}
void ClientInterface::startTCPSocket() {
FILE_LOG(logDEBUG) << "Creating TCP Server Thread";
killTCPServerThread = 0;
if (pthread_create(&TCPServer_thread, nullptr, startTCPServerThread,
(void *)this)) {
throw RuntimeError("Could not create TCP Server thread");
}
tcpThreadCreated = true;
FILE_LOG(logDEBUG) << "TCP Server thread created successfully.";
}
void ClientInterface::stopTCPSocket() {
if (tcpThreadCreated) {
FILE_LOG(logINFO) << "Shutting down TCP Socket on port " << portNumber;
killTCPServerThread = 1;
if (server)
server->shutDownSocket();
FILE_LOG(logDEBUG) << "TCP Socket closed on port " << portNumber;
pthread_join(TCPServer_thread, nullptr);
tcpThreadCreated = false;
killTCPServerThread = 0;
FILE_LOG(logDEBUG) << "Exiting TCP Server Thread on port "
<< portNumber;
}
: myDetectorType(GOTTHARD),
portNumber(portNumber > 0 ? portNumber : DEFAULT_PORTNO + 2) {
functionTable();
// start up tcp thread
tcpThread = sls::make_unique<std::thread>(&ClientInterface::startTCPServer, this);
}
int64_t ClientInterface::getReceiverVersion() { return APIRECEIVER; }
@ -81,14 +67,8 @@ void ClientInterface::registerCallBackRawDataModifyReady(
pRawDataReady = arg;
}
void *ClientInterface::startTCPServerThread(void *this_pointer) {
((ClientInterface *)this_pointer)->startTCPServer();
return this_pointer;
}
void ClientInterface::startTCPServer() {
FILE_LOG(logINFOBLUE) << "Created [ TCP server Tid: " << syscall(SYS_gettid)
<< "]";
FILE_LOG(logINFOBLUE) << "Created [ TCP server Tid: " << syscall(SYS_gettid) << "]";
FILE_LOG(logINFO) << "SLS Receiver starting TCP Server on port "
<< portNumber << '\n';
server = sls::make_unique<sls::ServerSocket>(portNumber);
@ -97,8 +77,8 @@ void ClientInterface::startTCPServer() {
try {
auto socket = server->accept();
try {
VerifyLock();
ret = decode_function(socket);
verifyLock();
ret = decodeFunction(socket);
} catch (const RuntimeError &e) {
// We had an error needs to be sent to client
char mess[MAX_STR_LENGTH]{};
@ -106,37 +86,27 @@ void ClientInterface::startTCPServer() {
socket.Send(FAIL);
socket.Send(mess);
}
// if tcp command was to exit server
if (ret == GOODBYE) {
FILE_LOG(logINFO) << "Shutting down UDP Socket";
if (receiver) {
receiver->shutDownUDPSockets();
}
FILE_LOG(logINFOBLUE)
<< "Exiting [ TCP server Tid: " << syscall(SYS_gettid)
<< "]";
pthread_exit(nullptr);
break;
}
} catch (const RuntimeError &e) {
FILE_LOG(logERROR) << "Accept failed";
}
// if user entered exit
if (killTCPServerThread) {
if (ret != GOODBYE) {
if (receiver) {
receiver->shutDownUDPSockets();
}
}
FILE_LOG(logINFOBLUE)
<< "Exiting [ TCP server Tid: " << syscall(SYS_gettid) << "]";
pthread_exit(nullptr);
// destructor to kill this thread
if (killTcpThread) {
break;
}
}
if (receiver) {
receiver->shutDownUDPSockets();
}
FILE_LOG(logINFOBLUE) << "Exiting [ TCP server Tid: " << syscall(SYS_gettid) << "]";
}
// clang-format off
int ClientInterface::function_table(){
int ClientInterface::functionTable(){
flist[F_EXEC_RECEIVER_COMMAND] = &ClientInterface::exec_command;
flist[F_EXIT_RECEIVER] = &ClientInterface::exit_server;
flist[F_LOCK_RECEIVER] = &ClientInterface::lock_receiver;
@ -203,37 +173,39 @@ int ClientInterface::function_table(){
flist[F_SET_RECEIVER_UDP_PORT] = &ClientInterface::set_udp_port;
flist[F_SET_RECEIVER_UDP_PORT2] = &ClientInterface::set_udp_port2;
flist[F_SET_RECEIVER_NUM_INTERFACES] = &ClientInterface::set_num_interfaces;
flist[F_RECEIVER_SET_ADC_MASK_10G] = &ClientInterface::set_adc_mask_10g;
flist[F_RECEIVER_SET_NUM_COUNTERS] = &ClientInterface::set_num_counters;
for (int i = NUM_DET_FUNCTIONS + 1; i < NUM_REC_FUNCTIONS ; i++) {
// FILE_LOG(logDEBUG1) << "function fnum: " << i << " (" <<
// getFunctionNameFromEnum((enum detFuncs)i) << ") located at " << flist[i];
FILE_LOG(logDEBUG1) << "function fnum: " << i << " (" <<
getFunctionNameFromEnum((enum detFuncs)i) << ") located at " << flist[i];
}
return OK;
}
// clang-format on
int ClientInterface::decode_function(Interface &socket) {
int ClientInterface::decodeFunction(Interface &socket) {
ret = FAIL;
socket.Receive(fnum);
if (fnum <= NUM_DET_FUNCTIONS || fnum >= NUM_REC_FUNCTIONS) {
throw RuntimeError("Unrecognized Function enum " +
std::to_string(fnum) + "\n");
} else {
// FILE_LOG(logDEBUG1) << "calling function fnum: " << fnum << " ("
// << getFunctionNameFromEnum((enum detFuncs)fnum)
// << ")";
FILE_LOG(logDEBUG1) << "calling function fnum: " << fnum << " ("
<< getFunctionNameFromEnum((enum detFuncs)fnum)
<< ")";
ret = (this->*flist[fnum])(socket);
// FILE_LOG(logDEBUG1)
// << "Function " << getFunctionNameFromEnum((enum detFuncs)fnum)
// << " finished";
FILE_LOG(logDEBUG1)
<< "Function " << getFunctionNameFromEnum((enum detFuncs)fnum)
<< " finished";
}
return ret;
}
void ClientInterface::functionNotImplemented() {
std::ostringstream os;
// os << "Function: " << getFunctionNameFromEnum((enum detFuncs)fnum)
// << ", is is not implemented for this detector";
os << "Function: " << getFunctionNameFromEnum((enum detFuncs)fnum)
<< ", is is not implemented for this detector";
throw RuntimeError(os.str());
}
@ -257,13 +229,13 @@ void ClientInterface::validate(T arg, T retval, std::string modename,
}
}
void ClientInterface::VerifyLock() {
if (lockStatus && server->getThisClient() != server->getLockedBy()) {
void ClientInterface::verifyLock() {
if (lockedByClient && server->getThisClient() != server->getLockedBy()) {
throw sls::SocketError("Receiver locked\n");
}
}
void ClientInterface::VerifyIdle(Interface &socket) {
void ClientInterface::verifyIdle(Interface &socket) {
if (impl()->getStatus() != IDLE) {
std::ostringstream oss;
oss << "Can not execute " << getFunctionNameFromEnum((enum detFuncs)fnum)
@ -304,15 +276,15 @@ int ClientInterface::lock_receiver(Interface &socket) {
auto lock = socket.Receive<int>();
FILE_LOG(logDEBUG1) << "Locking Server to " << lock;
if (lock >= 0) {
if (!lockStatus || (server->getLockedBy() == server->getThisClient())) {
lockStatus = lock;
if (!lockedByClient || (server->getLockedBy() == server->getThisClient())) {
lockedByClient = lock;
lock ? server->setLockedBy(server->getThisClient())
: server->setLockedBy(sls::IpAddr{});
} else {
throw RuntimeError("Receiver locked\n");
}
}
return socket.sendResult(lockStatus);
return socket.sendResult(lockedByClient);
}
int ClientInterface::get_last_client_ip(Interface &socket) {
@ -348,7 +320,7 @@ int ClientInterface::send_update(Interface &socket) {
int64_t i64 = -1;
char cstring[MAX_STR_LENGTH]{};
sls::IpAddr ip = 0u;
sls::IpAddr ip;
ip = server->getLastClient();
n += socket.Send(&ip, sizeof(ip));
@ -456,7 +428,7 @@ int ClientInterface::set_detector_type(Interface &socket) {
// if object exists, verify unlocked and idle, else only verify lock
// (connecting first time)
if (receiver != nullptr) {
VerifyIdle(socket);
verifyIdle(socket);
}
switch (arg) {
case GOTTHARD:
@ -471,11 +443,11 @@ int ClientInterface::set_detector_type(Interface &socket) {
break;
}
if (receiver == nullptr) {
receiver = sls::make_unique<Implementation>();
}
myDetectorType = arg;
if (impl()->setDetectorType(myDetectorType) == FAIL) {
try {
myDetectorType = GENERIC;
receiver = sls::make_unique<Implementation>(arg);
myDetectorType = arg;
} catch (...) {
throw RuntimeError("Could not set detector type");
}
@ -502,7 +474,7 @@ int ClientInterface::set_detector_hostname(Interface &socket) {
socket.Receive(hostname);
if (strlen(hostname) != 0) {
VerifyIdle(socket);
verifyIdle(socket);
impl()->setDetectorHostname(hostname);
}
auto s = impl()->getDetectorHostname();
@ -522,9 +494,12 @@ int ClientInterface::set_roi(Interface &socket) {
if (myDetectorType != GOTTHARD)
functionNotImplemented();
VerifyIdle(socket);
if (impl()->setROI(arg) == FAIL)
verifyIdle(socket);
try {
impl()->setROI(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set ROI");
}
return socket.Send(OK);
}
@ -541,7 +516,11 @@ int ClientInterface::set_num_analog_samples(Interface &socket) {
if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) {
functionNotImplemented();
}
ret = impl()->setNumberofAnalogSamples(value);
try {
impl()->setNumberofAnalogSamples(value);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set num analog samples to " + std::to_string(value) + " due to fifo structure memory allocation.");
}
return socket.Send(OK);
}
@ -552,7 +531,11 @@ int ClientInterface::set_num_digital_samples(Interface &socket) {
if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) {
functionNotImplemented();
}
ret = impl()->setNumberofDigitalSamples(value);
try {
impl()->setNumberofDigitalSamples(value);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set num digital samples to " + std::to_string(value) + " due to fifo structure memory allocation.");
}
return socket.Send(OK);
}
@ -588,7 +571,7 @@ int ClientInterface::set_subdeadtime(Interface &socket) {
int ClientInterface::set_dynamic_range(Interface &socket) {
auto dr = socket.Receive<int>();
if (dr >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting dynamic range: " << dr;
bool exists = false;
switch(myDetectorType) {
@ -611,8 +594,9 @@ int ClientInterface::set_dynamic_range(Interface &socket) {
if (!exists) {
modeNotImplemented("Dynamic range", dr);
} else {
ret = impl()->setDynamicRange(dr);
if (ret == FAIL) {
try {
impl()->setDynamicRange(dr);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not allocate memory for fifo or "
"could not start listening/writing threads");
}
@ -627,12 +611,9 @@ int ClientInterface::set_dynamic_range(Interface &socket) {
int ClientInterface::set_streaming_frequency(Interface &socket) {
auto index = socket.Receive<int>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming frequency: " << index;
ret = impl()->setStreamingFrequency(index);
if (ret == FAIL) {
throw RuntimeError("Could not allocate memory for listening fifo");
}
impl()->setStreamingFrequency(index);
}
int retval = impl()->getStreamingFrequency();
validate(index, retval, "set streaming frequency", DEC);
@ -648,11 +629,7 @@ int ClientInterface::get_status(Interface &socket) {
int ClientInterface::start_receiver(Interface &socket) {
if (impl()->getStatus() == IDLE) {
FILE_LOG(logDEBUG1) << "Starting Receiver";
std::string err;
ret = impl()->startReceiver(err);
if (ret == FAIL) {
throw RuntimeError(err);
}
impl()->startReceiver();
}
return socket.Send(OK);
}
@ -713,7 +690,7 @@ int ClientInterface::set_file_name(Interface &socket) {
int ClientInterface::set_file_index(Interface &socket) {
auto index = socket.Receive<int64_t>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting file index: " << index;
impl()->setFileIndex(index);
}
@ -750,7 +727,7 @@ int ClientInterface::get_frames_caught(Interface &socket) {
int ClientInterface::enable_file_write(Interface &socket) {
auto enable = socket.Receive<int>();
if (enable >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting File write enable:" << enable;
impl()->setFileWriteEnable(enable);
}
@ -763,7 +740,7 @@ int ClientInterface::enable_file_write(Interface &socket) {
int ClientInterface::enable_master_file_write(Interface &socket) {
auto enable = socket.Receive<int>();
if (enable >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting Master File write enable:" << enable;
impl()->setMasterFileWriteEnable(enable);
}
@ -776,7 +753,7 @@ int ClientInterface::enable_master_file_write(Interface &socket) {
int ClientInterface::enable_overwrite(Interface &socket) {
auto index = socket.Receive<int>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting File overwrite enable:" << index;
impl()->setOverwriteEnable(index);
}
@ -793,9 +770,13 @@ int ClientInterface::enable_tengiga(Interface &socket) {
functionNotImplemented();
if (val >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting 10GbE:" << val;
ret = impl()->setTenGigaEnable(val);
try {
impl()->setTenGigaEnable(val);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set 10GbE.");
}
}
int retval = impl()->getTenGigaEnable();
validate(val, retval, "set 10GbE", DEC);
@ -806,9 +787,13 @@ int ClientInterface::enable_tengiga(Interface &socket) {
int ClientInterface::set_fifo_depth(Interface &socket) {
auto value = socket.Receive<int>();
if (value >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting fifo depth:" << value;
impl()->setFifoDepth(value);
try {
impl()->setFifoDepth(value);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set fifo depth due to fifo structure memory allocation.");
}
}
int retval = impl()->getFifoDepth();
validate(value, retval, std::string("set fifo depth"), DEC);
@ -822,7 +807,7 @@ int ClientInterface::set_activate(Interface &socket) {
functionNotImplemented();
if (enable >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting activate:" << enable;
impl()->setActivate(static_cast<bool>(enable));
}
@ -835,9 +820,13 @@ int ClientInterface::set_activate(Interface &socket) {
int ClientInterface::set_data_stream_enable(Interface &socket) {
auto index = socket.Receive<int>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting data stream enable:" << index;
impl()->setDataStreamEnable(index);
try {
impl()->setDataStreamEnable(index);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set data stream enable to " + std::to_string(index));
}
}
auto retval = static_cast<int>(impl()->getDataStreamEnable());
validate(index, retval, "set data stream enable", DEC);
@ -848,7 +837,7 @@ int ClientInterface::set_data_stream_enable(Interface &socket) {
int ClientInterface::set_streaming_timer(Interface &socket) {
auto index = socket.Receive<int>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming timer:" << index;
impl()->setStreamingTimer(index);
}
@ -865,7 +854,7 @@ int ClientInterface::set_flipped_data(Interface &socket) {
functionNotImplemented();
if (arg >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting flipped data:" << arg;
impl()->setFlippedDataX(arg);
}
@ -879,7 +868,7 @@ int ClientInterface::set_file_format(Interface &socket) {
fileFormat f = GET_FILE_FORMAT;
socket.Receive(f);
if (f >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting file format:" << f;
impl()->setFileFormat(f);
}
@ -892,7 +881,7 @@ int ClientInterface::set_file_format(Interface &socket) {
int ClientInterface::set_detector_posid(Interface &socket) {
auto arg = socket.Receive<int>();
if (arg >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting detector position id:" << arg;
impl()->setDetectorPositionId(arg);
}
@ -906,7 +895,7 @@ int ClientInterface::set_multi_detector_size(Interface &socket) {
int arg[]{-1, -1};
socket.Receive(arg);
if ((arg[0] > 0) && (arg[1] > 0)) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1)
<< "Setting multi detector size:" << arg[0] << "," << arg[1];
impl()->setMultiDetectorSize(arg);
@ -920,7 +909,7 @@ int ClientInterface::set_multi_detector_size(Interface &socket) {
int ClientInterface::set_streaming_port(Interface &socket) {
auto port = socket.Receive<int>();
if (port >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming port:" << port;
impl()->setStreamingPort(port);
}
@ -931,9 +920,9 @@ int ClientInterface::set_streaming_port(Interface &socket) {
}
int ClientInterface::set_streaming_source_ip(Interface &socket) {
sls::IpAddr arg = 0u;
sls::IpAddr arg;
socket.Receive(arg);
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming source ip:" << arg;
impl()->setStreamingSourceIP(arg);
sls::IpAddr retval = impl()->getStreamingSourceIP();
@ -949,7 +938,7 @@ int ClientInterface::set_streaming_source_ip(Interface &socket) {
int ClientInterface::set_silent_mode(Interface &socket) {
auto value = socket.Receive<int>();
if (value >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting silent mode:" << value;
impl()->setSilentMode(value);
}
@ -965,9 +954,13 @@ int ClientInterface::enable_gap_pixels(Interface &socket) {
functionNotImplemented();
if (enable >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting gap pixels enable:" << enable;
impl()->setGapPixelsEnable(static_cast<bool>(enable));
try {
impl()->setGapPixelsEnable(static_cast<bool>(enable));
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set gap pixels enable to " + std::to_string(enable));
}
}
auto retval = static_cast<int>(impl()->getGapPixelsEnable());
validate(enable, retval, "set gap pixels enable", DEC);
@ -976,7 +969,7 @@ int ClientInterface::enable_gap_pixels(Interface &socket) {
}
int ClientInterface::restream_stop(Interface &socket) {
VerifyIdle(socket);
verifyIdle(socket);
if (!impl()->getDataStreamEnable()) {
throw RuntimeError(
"Could not restream stop packet as data Streaming is disabled");
@ -991,7 +984,7 @@ int ClientInterface::set_additional_json_header(Interface &socket) {
char arg[MAX_STR_LENGTH]{};
char retval[MAX_STR_LENGTH]{};
socket.Receive(arg);
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting additional json header: " << arg;
impl()->setAdditionalJsonHeader(arg);
sls::strcpy_safe(retval, impl()->getAdditionalJsonHeader().c_str());
@ -1009,12 +1002,9 @@ int ClientInterface::get_additional_json_header(Interface &socket) {
int ClientInterface::set_udp_socket_buffer_size(Interface &socket) {
auto index = socket.Receive<int64_t>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting UDP Socket Buffer size: " << index;
if (impl()->setUDPSocketBufferSize(index) == FAIL) {
throw RuntimeError(
"Could not create dummy UDP Socket to test buffer size");
}
impl()->setUDPSocketBufferSize(index);
}
int64_t retval = impl()->getUDPSocketBufferSize();
if (index != 0)
@ -1035,7 +1025,7 @@ int ClientInterface::get_real_udp_socket_buffer_size(
int ClientInterface::set_frames_per_file(Interface &socket) {
auto index = socket.Receive<int>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting frames per file: " << index;
impl()->setFramesPerFile(index);
}
@ -1076,7 +1066,7 @@ int ClientInterface::check_version_compatibility(Interface &socket) {
int ClientInterface::set_discard_policy(Interface &socket) {
auto index = socket.Receive<int>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting frames discard policy: " << index;
impl()->setFrameDiscardPolicy(static_cast<frameDiscardPolicy>(index));
}
@ -1089,7 +1079,7 @@ int ClientInterface::set_discard_policy(Interface &socket) {
int ClientInterface::set_padding_enable(Interface &socket) {
auto index = socket.Receive<int>();
if (index >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting frames padding enable: " << index;
impl()->setFramePaddingEnable(static_cast<bool>(index));
}
@ -1106,7 +1096,7 @@ int ClientInterface::set_deactivated_padding_enable(
functionNotImplemented();
if (enable >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting deactivated padding enable: " << enable;
impl()->setDeactivatedPadding(enable > 0);
}
@ -1123,9 +1113,13 @@ int ClientInterface::set_readout_mode(Interface &socket) {
functionNotImplemented();
if (arg >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting readout mode: " << arg;
impl()->setReadoutMode(arg);
try {
impl()->setReadoutMode(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set read out mode due to fifo memory allocation.");
}
}
auto retval = impl()->getReadoutMode();
validate(static_cast<int>(arg), static_cast<int>(retval),
@ -1136,17 +1130,21 @@ int ClientInterface::set_readout_mode(Interface &socket) {
int ClientInterface::set_adc_mask(Interface &socket) {
auto arg = socket.Receive<uint32_t>();
VerifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting ADC enable mask: " << arg;
impl()->setADCEnableMask(arg);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting 1Gb ADC enable mask: " << arg;
try {
impl()->setADCEnableMask(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set adc enable mask due to fifo memory allcoation");
}
auto retval = impl()->getADCEnableMask();
if (retval != arg) {
std::ostringstream os;
os << "Could not ADC enable mask. Set 0x" << std::hex << arg
os << "Could not set 1Gb ADC enable mask. Set 0x" << std::hex << arg
<< " but read 0x" << std::hex << retval;
throw RuntimeError(os.str());
}
FILE_LOG(logDEBUG1) << "ADC enable mask retval: " << retval;
FILE_LOG(logDEBUG1) << "1Gb ADC enable mask retval: " << retval;
return socket.sendResult(retval);
}
@ -1158,7 +1156,7 @@ int ClientInterface::set_dbit_list(Interface &socket) {
FILE_LOG(logDEBUG1) << it << " ";
}
FILE_LOG(logDEBUG1) << "\n";
VerifyIdle(socket);
verifyIdle(socket);
impl()->setDbitList(args);
return socket.Send(OK);
}
@ -1173,7 +1171,7 @@ int ClientInterface::get_dbit_list(Interface &socket) {
int ClientInterface::set_dbit_offset(Interface &socket) {
auto arg = socket.Receive<int>();
if (arg >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting Dbit offset: " << arg;
impl()->setDbitOffset(arg);
}
@ -1186,12 +1184,13 @@ int ClientInterface::set_dbit_offset(Interface &socket) {
int ClientInterface::set_quad_type(Interface &socket) {
auto quadEnable = socket.Receive<int>();
if (quadEnable >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting quad:" << quadEnable;
ret = impl()->setQuad(quadEnable == 0 ? false : true);
if (ret == FAIL) {
throw RuntimeError("Could not set Quad due to fifo structure");
}
try {
impl()->setQuad(quadEnable == 0 ? false : true);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set quad to " + std::to_string(quadEnable) + " due to fifo strucutre memory allocation");
}
}
int retval = impl()->getQuad() ? 1 : 0;
validate(quadEnable, retval, "set quad", DEC);
@ -1202,7 +1201,7 @@ int ClientInterface::set_quad_type(Interface &socket) {
int ClientInterface::set_read_n_lines(Interface &socket) {
auto arg = socket.Receive<int>();
if (arg >= 0) {
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting Read N Lines:" << arg;
impl()->setReadNLines(arg);
}
@ -1215,7 +1214,7 @@ int ClientInterface::set_read_n_lines(Interface &socket) {
int ClientInterface::set_udp_ip(Interface &socket) {
auto arg = socket.Receive<sls::IpAddr>();
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logINFO) << "Received UDP IP: " << arg;
// getting eth
std::string eth = sls::IpToInterfaceName(arg.str());
@ -1242,7 +1241,7 @@ int ClientInterface::set_udp_ip(Interface &socket) {
int ClientInterface::set_udp_ip2(Interface &socket) {
auto arg = socket.Receive<sls::IpAddr>();
VerifyIdle(socket);
verifyIdle(socket);
if (myDetectorType != JUNGFRAU) {
throw RuntimeError("UDP Destination IP2 not implemented for this detector");
}
@ -1269,7 +1268,7 @@ int ClientInterface::set_udp_ip2(Interface &socket) {
int ClientInterface::set_udp_port(Interface &socket) {
auto arg = socket.Receive<int>();
VerifyIdle(socket);
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting UDP Port:" << arg;
impl()->setUDPPortNumber(arg);
return socket.Send(OK);
@ -1277,7 +1276,7 @@ int ClientInterface::set_udp_port(Interface &socket) {
int ClientInterface::set_udp_port2(Interface &socket) {
auto arg = socket.Receive<int>();
VerifyIdle(socket);
verifyIdle(socket);
if (myDetectorType != JUNGFRAU && myDetectorType != EIGER) {
throw RuntimeError("UDP Destination Port2 not implemented for this detector");
}
@ -1289,13 +1288,43 @@ int ClientInterface::set_udp_port2(Interface &socket) {
int ClientInterface::set_num_interfaces(Interface &socket) {
auto arg = socket.Receive<int>();
arg = (arg > 1 ? 2 : 1);
VerifyIdle(socket);
verifyIdle(socket);
if (myDetectorType != JUNGFRAU) {
throw RuntimeError("Number of interfaces not implemented for this detector");
}
FILE_LOG(logDEBUG1) << "Setting Number of UDP Interfaces:" << arg;
if (impl()->setNumberofUDPInterfaces(arg) == FAIL) {
throw RuntimeError("Failed to set number of interfaces");
try {
impl()->setNumberofUDPInterfaces(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Failed to set number of interfaces to " + std::to_string(arg));
}
return socket.Send(OK);
}
int ClientInterface::set_adc_mask_10g(Interface &socket) {
auto arg = socket.Receive<uint32_t>();
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting 10Gb ADC enable mask: " << arg;
try {
impl()->setTenGigaADCEnableMask(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set 10Gb adc enable mask due to fifo memory allcoation");
}
auto retval = impl()->getTenGigaADCEnableMask();
if (retval != arg) {
std::ostringstream os;
os << "Could not 10gb ADC enable mask. Set 0x" << std::hex << arg
<< " but read 0x" << std::hex << retval;
throw RuntimeError(os.str());
}
FILE_LOG(logDEBUG1) << "10Gb ADC enable mask retval: " << retval;
return socket.sendResult(retval);
}
int ClientInterface::set_num_counters(Interface &socket) {
auto arg = socket.Receive<int>();
verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting counters: " << arg;
impl()->setNumberofCounters(arg);
return socket.Send(OK);
}

View File

@ -30,7 +30,7 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f,
bool* fp, bool* act, bool* depaden, bool* sm, bool* qe,
std::vector <int> * cdl, int* cdo, int* cad) :
ThreadObject(ind),
ThreadObject(ind, TypeName),
runningFlag(false),
generalData(nullptr),
fifo(f),
@ -62,11 +62,7 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f,
rawDataModifyReadyCallBack(nullptr),
pRawDataReady(nullptr)
{
if(ThreadObject::CreateThread() == FAIL)
throw sls::RuntimeError("Could not create processing thread");
FILE_LOG(logDEBUG) << "DataProcessor " << ind << " created";
memset((void*)&timerBegin, 0, sizeof(timespec));
}
@ -74,13 +70,9 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f,
DataProcessor::~DataProcessor() {
delete file;
delete [] tempBuffer;
ThreadObject::DestroyThread();
}
/** getters */
std::string DataProcessor::GetType(){
return TypeName;
}
bool DataProcessor::IsRunning() {
return runningFlag;
@ -158,16 +150,6 @@ void DataProcessor::SetGeneralData(GeneralData* g) {
}
int DataProcessor::SetThreadPriority(int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(thread, SCHED_FIFO, &param) == EPERM)
return FAIL;
FILE_LOG(logINFO) << "Processor Thread Priority set to " << priority;
return OK;
}
void DataProcessor::SetFileFormat(const fileFormat f) {
if ((file != nullptr) && file->GetFileType() != f) {
//remember the pointer values before they are destroyed
@ -220,16 +202,14 @@ void DataProcessor::SetupFileWriter(bool fwe, int* nd, uint32_t* maxf,
}
// only the first file
int DataProcessor::CreateNewFile(masterAttributes& attr) {
if (file == nullptr)
return FAIL;
void DataProcessor::CreateNewFile(masterAttributes& attr) {
if (file == nullptr) {
throw sls::RuntimeError("file object not contstructed");
}
file->CloseAllFiles();
file->resetSubFileIndex();
if (file->CreateMasterFile(*masterFileWriteEnable, attr) == FAIL)
return FAIL;
if (file->CreateFile() == FAIL)
return FAIL;
return OK;
file->CreateMasterFile(*masterFileWriteEnable, attr);
file->CreateFile();
}
@ -240,7 +220,11 @@ void DataProcessor::CloseFiles() {
void DataProcessor::EndofAcquisition(bool anyPacketsCaught, uint64_t numf) {
if ((file != nullptr) && file->GetFileType() == HDF5) {
file->EndofAcquisition(anyPacketsCaught, numf);
try {
file->EndofAcquisition(anyPacketsCaught, numf);
} catch (const sls::RuntimeError &e) {
;// ignore for now //TODO: send error to client via stop receiver
}
}
}
@ -352,10 +336,15 @@ void DataProcessor::ProcessAnImage(char* buf) {
// write to file
if (file != nullptr)
file->WriteToFile(buf + FIFO_HEADER_NUMBYTES,
sizeof(sls_receiver_header) + (uint32_t)(*((uint32_t*)buf)), //+ size of data (resizable from previous call back
fnum-firstIndex, nump);
if (file != nullptr) {
try {
file->WriteToFile(buf + FIFO_HEADER_NUMBYTES,
sizeof(sls_receiver_header) + (uint32_t)(*((uint32_t*)buf)), //+ size of data (resizable from previous call back
fnum-firstIndex, nump);
} catch(const sls::RuntimeError &e) {
; //ignore write exception for now (TODO: send error message via stopReceiver tcp)
}
}
}

View File

@ -18,7 +18,7 @@ const std::string DataStreamer::TypeName = "DataStreamer";
DataStreamer::DataStreamer(int ind, Fifo* f, uint32_t* dr, ROI* r,
uint64_t* fi, int fd, std::string* ajh, int* nd, bool* gpEnable, bool* qe) :
ThreadObject(ind),
ThreadObject(ind, TypeName),
runningFlag(0),
generalData(nullptr),
fifo(f),
@ -38,25 +38,16 @@ DataStreamer::DataStreamer(int ind, Fifo* f, uint32_t* dr, ROI* r,
numDet[0] = nd[0];
numDet[1] = nd[1];
if(ThreadObject::CreateThread() == FAIL)
throw sls::RuntimeError("Could not create streaming thread");
FILE_LOG(logDEBUG) << "DataStreamer " << ind << " created";
// memset(fileNametoStream, 0, MAX_STR_LENGTH);
}
DataStreamer::~DataStreamer() {
CloseZmqSocket();
delete [] completeBuffer;
ThreadObject::DestroyThread();
}
/** getters */
std::string DataStreamer::GetType(){
return TypeName;
}
bool DataStreamer::IsRunning() {
return runningFlag;
@ -82,7 +73,6 @@ void DataStreamer::ResetParametersforNewAcquisition(const std::string& fname){
startedFlag = false;
firstIndex = 0;
// strcpy(fileNametoStream, fname);
fileNametoStream = fname;
if (completeBuffer) {
delete[] completeBuffer;
@ -109,15 +99,6 @@ void DataStreamer::SetGeneralData(GeneralData* g) {
generalData->Print();
}
int DataStreamer::SetThreadPriority(int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(thread, SCHED_FIFO, &param) == EPERM)
return FAIL;
FILE_LOG(logINFO) << "Streamer Thread Priority set to " << priority;
return OK;
}
void DataStreamer::SetNumberofDetectors(int* nd) {
numDet[0] = nd[0];
numDet[1] = nd[1];
@ -258,14 +239,12 @@ int DataStreamer::SendHeader(sls_receiver_header* rheader, uint32_t size, uint32
int DataStreamer::RestreamStop() {
void DataStreamer::RestreamStop() {
//send dummy header
int ret = zmqSocket->SendHeaderData(index, true, SLS_DETECTOR_JSON_HEADER_VERSION);
if (!ret) {
FILE_LOG(logERROR) << "Could not Restream Dummy Header via ZMQ for port " << zmqSocket->GetPortNumber();
return FAIL;
throw sls::RuntimeError("Could not restream Dummy Header via ZMQ for port " + std::to_string(zmqSocket->GetPortNumber()));
}
return OK;
}

View File

@ -23,8 +23,7 @@ Fifo::Fifo(int ind, uint32_t fifoItemSize, uint32_t depth):
status_fifoBound(0),
status_fifoFree(depth){
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
if(CreateFifos(fifoItemSize) == FAIL)
throw sls::RuntimeError("Could not create FIFO");
CreateFifos(fifoItemSize);
}
@ -35,7 +34,7 @@ Fifo::~Fifo() {
int Fifo::CreateFifos(uint32_t fifoItemSize) {
void Fifo::CreateFifos(uint32_t fifoItemSize) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
//destroy if not already
@ -49,8 +48,7 @@ int Fifo::CreateFifos(uint32_t fifoItemSize) {
size_t mem_len = fifoItemSize * fifoDepth * sizeof(char);
memory = (char*) malloc (mem_len);
if (memory == nullptr){
FILE_LOG(logERROR) << "Could not allocate memory for fifos";
return FAIL;
throw sls::RuntimeError("Could not allocate memory for fifos");
}
memset(memory, 0, mem_len);
FILE_LOG(logDEBUG) << "Memory Allocated " << index << ": " << mem_len << " bytes";
@ -64,7 +62,6 @@ int Fifo::CreateFifos(uint32_t fifoItemSize) {
}
}
FILE_LOG(logINFO) << "Fifo " << index << " reconstructed Depth (rx_fifodepth): " << fifoFree->getDataValue();
return OK;
}

View File

@ -13,7 +13,6 @@
#include <string.h>
pthread_mutex_t HDF5File::Mutex = PTHREAD_MUTEX_INITIALIZER;
H5File* HDF5File::masterfd = 0;
hid_t HDF5File::virtualfd = 0;
@ -128,7 +127,7 @@ void HDF5File::UpdateDataType() {
}
int HDF5File::CreateFile() {
void HDF5File::CreateFile() {
numFilesinAcquisition++;
numFramesInFile = 0;
numActualPacketsInFile = 0;
@ -142,29 +141,26 @@ int HDF5File::CreateFile() {
uint64_t framestosave = ((*maxFramesPerFile == 0) ? *numImages : // infinite images
(((extNumImages - subFileIndex) > (*maxFramesPerFile)) ? // save up to maximum at a time
(*maxFramesPerFile) : (extNumImages-subFileIndex)));
pthread_mutex_lock(&Mutex);
if (HDF5FileStatic::CreateDataFile(index, *overWriteEnable, currentFileName, (*numImages > 1),
std::lock_guard<std::mutex> lock(mutex);
HDF5FileStatic::CreateDataFile(index, *overWriteEnable, currentFileName, (*numImages > 1),
subFileIndex, framestosave, nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX),
datatype, filefd, dataspace, dataset,
HDF5_WRITER_VERSION, MAX_CHUNKED_IMAGES,
dataspace_para, dataset_para,
parameterNames, parameterDataTypes) == FAIL) {
pthread_mutex_unlock(&Mutex);
return FAIL;
}
pthread_mutex_unlock(&Mutex);
parameterNames, parameterDataTypes);
if(!(*silentMode)) {
FILE_LOG(logINFO) << *udpPortNumber << ": HDF5 File created: " << currentFileName;
}
return OK;
}
void HDF5File::CloseCurrentFile() {
pthread_mutex_lock(&Mutex);
HDF5FileStatic::CloseDataFile(index, filefd);
pthread_mutex_unlock(&Mutex);
{
std::lock_guard<std::mutex> lock(mutex);
HDF5FileStatic::CloseDataFile(index, filefd);
}
for (unsigned int i = 0; i < dataset_para.size(); ++i)
delete dataset_para[i];
dataset_para.clear();
@ -177,14 +173,14 @@ void HDF5File::CloseCurrentFile() {
void HDF5File::CloseAllFiles() {
numFilesinAcquisition = 0;
pthread_mutex_lock(&Mutex);
HDF5FileStatic::CloseDataFile(index, filefd);
if (master && (*detIndex==0)) {
HDF5FileStatic::CloseMasterDataFile(masterfd);
HDF5FileStatic::CloseVirtualDataFile(virtualfd);
{
std::lock_guard<std::mutex> lock(mutex);
HDF5FileStatic::CloseDataFile(index, filefd);
if (master && (*detIndex==0)) {
HDF5FileStatic::CloseMasterDataFile(masterfd);
HDF5FileStatic::CloseVirtualDataFile(virtualfd);
}
}
pthread_mutex_unlock(&Mutex);
for (unsigned int i = 0; i < dataset_para.size(); ++i)
delete dataset_para[i];
dataset_para.clear();
@ -195,7 +191,7 @@ void HDF5File::CloseAllFiles() {
}
int HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) {
void HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) {
// check if maxframesperfile = 0 for infinite
if ((*maxFramesPerFile) && (numFramesInFile >= (*maxFramesPerFile))) {
@ -205,42 +201,35 @@ int HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t
}
numFramesInFile++;
numActualPacketsInFile += nump;
pthread_mutex_lock(&Mutex);
std::lock_guard<std::mutex> lock(mutex);
// extend dataset (when receiver start followed by many status starts (jungfrau)))
if (fnum >= extNumImages) {
if (HDF5FileStatic::ExtendDataset(index, dataspace, dataset,
dataspace_para, dataset_para, *numImages) == OK) {
if (!(*silentMode)) {
FILE_LOG(logINFO) << index << " Extending HDF5 dataset by " <<
extNumImages << ", Total x Dimension: " << (extNumImages + *numImages);
}
extNumImages += *numImages;
HDF5FileStatic::ExtendDataset(index, dataspace, dataset,
dataspace_para, dataset_para, *numImages);
if (!(*silentMode)) {
FILE_LOG(logINFO) << index << " Extending HDF5 dataset by " <<
extNumImages << ", Total x Dimension: " << (extNumImages + *numImages);
}
extNumImages += *numImages;
}
if (HDF5FileStatic::WriteDataFile(index, buffer + sizeof(sls_receiver_header),
HDF5FileStatic::WriteDataFile(index, buffer + sizeof(sls_receiver_header),
// infinite then no need for %maxframesperfile
((*maxFramesPerFile == 0) ? fnum : fnum%(*maxFramesPerFile)),
nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX),
dataspace, dataset, datatype) == OK) {
dataspace, dataset, datatype);
if (HDF5FileStatic::WriteParameterDatasets(index, dataspace_para,
HDF5FileStatic::WriteParameterDatasets(index, dataspace_para,
// infinite then no need for %maxframesperfile
((*maxFramesPerFile == 0) ? fnum : fnum%(*maxFramesPerFile)),
dataset_para, (sls_receiver_header*) (buffer),
parameterDataTypes) == OK) {
pthread_mutex_unlock(&Mutex);
return OK;
}
}
pthread_mutex_unlock(&Mutex);
FILE_LOG(logERROR) << index << "Write to file failed";
return FAIL;
parameterDataTypes);
}
int HDF5File::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
void HDF5File::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
//beginning of every acquisition
numFramesInFile = 0;
@ -254,14 +243,11 @@ int HDF5File::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
if(!(*silentMode)) {
FILE_LOG(logINFO) << "Master File: " << masterFileName;
}
pthread_mutex_lock(&Mutex);
std::lock_guard<std::mutex> lock(mutex);
attr.version = HDF5_WRITER_VERSION;
int ret = HDF5FileStatic::CreateMasterDataFile(masterfd, masterFileName,
HDF5FileStatic::CreateMasterDataFile(masterfd, masterFileName,
*overWriteEnable, attr);
pthread_mutex_unlock(&Mutex);
return ret;
}
return OK;
}
@ -286,15 +272,14 @@ void HDF5File::EndofAcquisition(bool anyPacketsCaught, uint64_t numf) {
// called only by the one maser receiver
int HDF5File::CreateVirtualFile(uint64_t numf) {
pthread_mutex_lock(&Mutex);
void HDF5File::CreateVirtualFile(uint64_t numf) {
std::lock_guard<std::mutex> lock(mutex);
std::string vname = HDF5FileStatic::CreateVirtualFileName(*filePath, *fileNamePrefix, *fileIndex);
if(!(*silentMode)) {
FILE_LOG(logINFO) << "Virtual File: " << vname;
}
int ret = HDF5FileStatic::CreateVirtualDataFile(vname,
HDF5FileStatic::CreateVirtualDataFile(vname,
virtualfd, masterFileName,
*filePath, *fileNamePrefix, *fileIndex, (*numImages > 1),
*detIndex, *numUnitsPerDetector,
@ -305,21 +290,17 @@ int HDF5File::CreateVirtualFile(uint64_t numf) {
numDetY, numDetX, nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX),
HDF5_WRITER_VERSION,
parameterNames, parameterDataTypes);
pthread_mutex_unlock(&Mutex);
return ret;
}
// called only by the one maser receiver
int HDF5File::LinkVirtualFileinMasterFile() {
void HDF5File::LinkVirtualFileinMasterFile() {
//dataset name
std::ostringstream osfn;
osfn << "/data";
if ((*numImages > 1)) osfn << "_f" << std::setfill('0') << std::setw(12) << 0;
std::string dsetname = osfn.str();
pthread_mutex_lock(&Mutex);
int ret = HDF5FileStatic::LinkVirtualInMaster(masterFileName, currentFileName,
std::lock_guard<std::mutex> lock(mutex);
HDF5FileStatic::LinkVirtualInMaster(masterFileName, currentFileName,
dsetname, parameterNames);
pthread_mutex_unlock(&Mutex);
return ret;
}

View File

@ -18,9 +18,10 @@
/** cosntructor & destructor */
Implementation::Implementation() {
Implementation::Implementation(const detectorType d) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
InitializeMembers();
setDetectorType(d);
}
Implementation::~Implementation() {
@ -89,7 +90,7 @@ void Implementation::InitializeMembers() {
streamingFrequency = 1;
streamingTimerInMs = DEFAULT_STREAMING_TIMER_IN_MS;
streamingPort = 0;
streamingSrcIP = 0u;
streamingSrcIP = sls::IpAddr{};
additionalJsonHeader = "";
// detector parameters
@ -100,6 +101,7 @@ void Implementation::InitializeMembers() {
subPeriod = 0;
numberOfAnalogSamples = 0;
numberOfDigitalSamples = 0;
numberOfCounters = 0;
dynamicRange = 16;
roi.xmin = -1;
roi.xmax = -1;
@ -111,7 +113,9 @@ void Implementation::InitializeMembers() {
deactivatedPaddingEnable = true;
numLinesReadout = MAX_EIGER_ROWS_PER_READOUT;
readoutType = ANALOG_ONLY;
adcEnableMask = BIT32_MASK;
adcEnableMaskOneGiga = BIT32_MASK;
adcEnableMaskTenGiga = BIT32_MASK;
ctbDbitOffset = 0;
ctbAnalogDataBytes = 0;
@ -158,23 +162,12 @@ void Implementation::SetLocalNetworkParameters() {
void Implementation::SetThreadPriorities() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
for (const auto &it : listener) {
if (it->SetThreadPriority(LISTENER_PRIORITY) == FAIL) {
FILE_LOG(logWARNING) << "Could not prioritize listener threads. "
"(No Root Privileges?)";
return;
}
it->SetThreadPriority(LISTENER_PRIORITY);
}
std::ostringstream osfn;
osfn << "Priorities set - "
"Listener:"
<< LISTENER_PRIORITY;
FILE_LOG(logINFO) << osfn.str();
}
int Implementation::SetupFifoStructure() {
void Implementation::SetupFifoStructure() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
fifo.clear();
@ -187,11 +180,8 @@ int Implementation::SetupFifoStructure() {
(generalData->imageSize) + (generalData->fifoBufferHeaderSize),
fifoDepth));
} catch (...) {
FILE_LOG(logERROR)
<< "Could not allocate memory for fifo structure of index "
<< i;
fifo.clear();
return FAIL;
throw sls::RuntimeError("Could not allocate memory for fifo structure " + std::to_string(i));
}
// set the listener & dataprocessor threads to point to the right fifo
if (listener.size())
@ -208,7 +198,6 @@ int Implementation::SetupFifoStructure() {
fifoDepth)
<< " bytes";
FILE_LOG(logINFO) << numThreads << " Fifo structure(s) reconstructed";
return OK;
}
@ -219,10 +208,8 @@ int Implementation::SetupFifoStructure() {
* *
* ************************************************/
int Implementation::setDetectorType(const detectorType d) {
void Implementation::setDetectorType(const detectorType d) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
DeleteMembers();
InitializeMembers();
myDetectorType = d;
switch (myDetectorType) {
case GOTTHARD:
@ -235,8 +222,7 @@ int Implementation::setDetectorType(const detectorType d) {
<< " Receiver *****";
break;
default:
FILE_LOG(logERROR) << "This is an unknown receiver type " << (int)d;
return FAIL;
throw sls::RuntimeError("This is an unknown receiver type " + std::to_string(static_cast<int>(d)));
}
// set detector specific variables
@ -268,10 +254,7 @@ int Implementation::setDetectorType(const detectorType d) {
framesPerFile = generalData->maxFramesPerFile;
SetLocalNetworkParameters();
if (SetupFifoStructure() == FAIL) {
FILE_LOG(logERROR) << "Could not allocate memory for fifo structure";
return FAIL;
}
SetupFifoStructure();
// create threads
for (int i = 0; i < numThreads; ++i) {
@ -291,12 +274,9 @@ int Implementation::setDetectorType(const detectorType d) {
&silentMode, &quadEnable, &ctbDbitList, &ctbDbitOffset,
&ctbAnalogDataBytes));
} catch (...) {
FILE_LOG(logERROR)
<< "Could not create listener/dataprocessor threads (index:"
<< i << ")";
listener.clear();
dataProcessor.clear();
return FAIL;
throw sls::RuntimeError("Could not create listener/dataprocessor threads (index:" + std::to_string(i) + ")");
}
}
@ -309,7 +289,6 @@ int Implementation::setDetectorType(const detectorType d) {
SetThreadPriorities();
FILE_LOG(logDEBUG) << " Detector type set to " << sls::ToString(d);
return OK;
}
int *Implementation::getMultiDetectorSize() const {
@ -402,14 +381,12 @@ uint32_t Implementation::getFifoDepth() const {
return fifoDepth;
}
int Implementation::setFifoDepth(const uint32_t i) {
void Implementation::setFifoDepth(const uint32_t i) {
if (fifoDepth != i) {
fifoDepth = i;
if (SetupFifoStructure() == FAIL)
throw sls::RuntimeError("Failed to setup fifo structure");
SetupFifoStructure();
}
FILE_LOG(logINFO) << "Fifo Depth: " << i;
return OK;
}
slsDetectorDefs::frameDiscardPolicy
@ -623,18 +600,14 @@ std::vector<uint64_t> Implementation::getNumMissingPackets() const {
return mp;
}
int Implementation::startReceiver(std::string& err) {
void Implementation::startReceiver() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
FILE_LOG(logINFO) << "Starting Receiver";
stoppedFlag = false;
ResetParametersforNewAcquisition();
// listener
if (CreateUDPSockets() == FAIL) {
err.assign("Could not create UDP Socket(s).");
FILE_LOG(logERROR) << err;
return FAIL;
}
CreateUDPSockets();
// callbacks
if (startAcquisitionCallBack) {
@ -649,11 +622,7 @@ int Implementation::startReceiver(std::string& err) {
// processor->writer
if (fileWriteEnable) {
if (SetupWriter() == FAIL) {
err.assign("Could not create file.\n");
FILE_LOG(logERROR) << err;
return FAIL;
}
SetupWriter();
} else
FILE_LOG(logINFO) << "File Write Disabled";
@ -667,7 +636,6 @@ int Implementation::startReceiver(std::string& err) {
FILE_LOG(logINFO) << "Receiver Started";
FILE_LOG(logINFO) << "Status: " << sls::ToString(status);
return OK;
}
void Implementation::setStoppedFlag(bool stopped) {
@ -815,14 +783,12 @@ void Implementation::closeFiles() {
dataProcessor[0]->EndofAcquisition(anycaught, maxIndexCaught);
}
int Implementation::restreamStop() {
void Implementation::restreamStop() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
for (const auto &it : dataStreamer) {
if (it->RestreamStop() == FAIL)
throw sls::RuntimeError("Could not restream stop packet");
it->RestreamStop();
}
FILE_LOG(logINFO) << "Restreaming Dummy Header via ZMQ successful";
return OK;
}
void Implementation::ResetParametersforNewAcquisition() {
@ -842,29 +808,23 @@ void Implementation::ResetParametersforNewAcquisition() {
}
}
int Implementation::CreateUDPSockets() {
void Implementation::CreateUDPSockets() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
bool error = false;
for (unsigned int i = 0; i < listener.size(); ++i) {
if (listener[i]->CreateUDPSockets() == FAIL) {
error = true;
break;
try{
for (unsigned int i = 0; i < listener.size(); ++i) {
listener[i]->CreateUDPSockets();
}
}
if (error) {
} catch(const sls::RuntimeError &e) {
shutDownUDPSockets();
return FAIL;
throw sls::RuntimeError("Could not create UDP Socket(s).");
}
FILE_LOG(logDEBUG) << "UDP socket(s) created successfully.";
return OK;
}
int Implementation::SetupWriter() {
void Implementation::SetupWriter() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
bool error = false;
masterAttributes attr;
attr.detectorType = myDetectorType;
attr.dynamicRange = dynamicRange;
@ -882,7 +842,7 @@ int Implementation::SetupWriter() {
attr.quadEnable = quadEnable;
attr.analogFlag = (readoutType == ANALOG_ONLY || readoutType == ANALOG_AND_DIGITAL) ? 1 : 0;
attr.digitalFlag = (readoutType == DIGITAL_ONLY || readoutType == ANALOG_AND_DIGITAL) ? 1 : 0;
attr.adcmask = adcEnableMask;
attr.adcmask = tengigaEnable ? adcEnableMaskTenGiga : adcEnableMaskOneGiga;
attr.dbitoffset = ctbDbitOffset;
attr.dbitlist = 0;
attr.roiXmin = roi.xmin;
@ -890,18 +850,16 @@ int Implementation::SetupWriter() {
for (auto &i : ctbDbitList) {
attr.dbitlist |= (1 << i);
}
for (unsigned int i = 0; i < dataProcessor.size(); ++i)
if (dataProcessor[i]->CreateNewFile(attr) == FAIL) {
error = true;
break;
try {
for (unsigned int i = 0; i < dataProcessor.size(); ++i) {
dataProcessor[i]->CreateNewFile(attr);
}
if (error) {
} catch(const sls::RuntimeError &e) {
shutDownUDPSockets();
closeFiles();
return FAIL;
throw sls::RuntimeError("Could not create file.");
}
return OK;
}
void Implementation::StartRunning() {
@ -933,7 +891,7 @@ int Implementation::getNumberofUDPInterfaces() const {
return numUDPInterfaces;
}
int Implementation::setNumberofUDPInterfaces(const int n) {
void Implementation::setNumberofUDPInterfaces(const int n) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
if (numUDPInterfaces != n) {
@ -957,8 +915,7 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
udpSocketBufferSize = generalData->defaultUdpSocketBufferSize;
// fifo
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
// create threads
for (int i = 0; i < numThreads; ++i) {
@ -982,12 +939,9 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
&ctbDbitOffset, &ctbAnalogDataBytes));
dataProcessor[i]->SetGeneralData(generalData);
} catch (...) {
FILE_LOG(logERROR)
<< "Could not create listener/dataprocessor threads (index:"
<< i << ")";
listener.clear();
dataProcessor.clear();
return FAIL;
throw sls::RuntimeError("Could not create listener/dataprocessor threads (index:" + std::to_string(i) + ")");
}
// streamer threads
if (dataStreamEnable) {
@ -1007,14 +961,11 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
&numThreads, streamingPort, streamingSrcIP);
} catch (...) {
FILE_LOG(logERROR)
<< "Could not create datastreamer threads (index:" << i
<< ")";
if (dataStreamEnable) {
dataStreamer.clear();
dataStreamEnable = false;
}
return FAIL;
throw sls::RuntimeError("Could not create datastreamer threads (index:" + std::to_string(i) + ")");
}
}
}
@ -1039,13 +990,10 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
}
// test socket buffer size with current set up
if (setUDPSocketBufferSize(0) == FAIL) {
return FAIL;
}
setUDPSocketBufferSize(0);
}
FILE_LOG(logINFO) << "Number of Interfaces: " << numUDPInterfaces;
return OK;
}
std::string Implementation::getEthernetInterface() const {
@ -1101,22 +1049,17 @@ int64_t Implementation::getUDPSocketBufferSize() const {
return udpSocketBufferSize;
}
int Implementation::setUDPSocketBufferSize(const int64_t s) {
void Implementation::setUDPSocketBufferSize(const int64_t s) {
int64_t size = (s == 0) ? udpSocketBufferSize : s;
size_t listSize = listener.size();
if (myDetectorType == JUNGFRAU && (int)listSize != numUDPInterfaces) {
FILE_LOG(logERROR) << "Number of Interfaces " << numUDPInterfaces
<< " do not match listener size " << listSize;
return FAIL;
throw sls::RuntimeError("Number of Interfaces " + std::to_string(numUDPInterfaces) + " do not match listener size " + std::to_string(listSize));
}
for (unsigned int i = 0; i < listSize; ++i) {
if (listener[i]->CreateDummySocketForUDPSocketBufferSize(size) == FAIL)
return FAIL;
listener[i]->CreateDummySocketForUDPSocketBufferSize(size);
}
return OK;
}
int64_t Implementation::getActualUDPSocketBufferSize() const {
@ -1135,7 +1078,7 @@ bool Implementation::getDataStreamEnable() const {
return dataStreamEnable;
}
int Implementation::setDataStreamEnable(const bool enable) {
void Implementation::setDataStreamEnable(const bool enable) {
if (dataStreamEnable != enable) {
dataStreamEnable = enable;
@ -1162,14 +1105,13 @@ int Implementation::setDataStreamEnable(const bool enable) {
} catch (...) {
dataStreamer.clear();
dataStreamEnable = false;
return FAIL;
throw sls::RuntimeError("Could not set data stream enable.");
}
}
SetThreadPriorities();
}
}
FILE_LOG(logINFO) << "Data Send to Gui: " << dataStreamEnable;
return OK;
}
uint32_t Implementation::getStreamingFrequency() const {
@ -1177,12 +1119,11 @@ uint32_t Implementation::getStreamingFrequency() const {
return streamingFrequency;
}
int Implementation::setStreamingFrequency(const uint32_t freq) {
void Implementation::setStreamingFrequency(const uint32_t freq) {
if (streamingFrequency != freq) {
streamingFrequency = freq;
}
FILE_LOG(logINFO) << "Streaming Frequency: " << streamingFrequency;
return OK;
}
uint32_t Implementation::getStreamingTimer() const {
@ -1305,23 +1246,22 @@ uint32_t Implementation::getNumberofAnalogSamples() const {
return numberOfAnalogSamples;
}
int Implementation::setNumberofAnalogSamples(const uint32_t i) {
void Implementation::setNumberofAnalogSamples(const uint32_t i) {
if (numberOfAnalogSamples != i) {
numberOfAnalogSamples = i;
ctbAnalogDataBytes = generalData->setImageSize(
adcEnableMask, numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable ? adcEnableMaskTenGiga : adcEnableMaskOneGiga,
numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable, readoutType);
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
FILE_LOG(logINFO) << "Number of Analog Samples: " << numberOfAnalogSamples;
FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame);
return OK;
}
uint32_t Implementation::getNumberofDigitalSamples() const {
@ -1329,24 +1269,43 @@ uint32_t Implementation::getNumberofDigitalSamples() const {
return numberOfDigitalSamples;
}
int Implementation::setNumberofDigitalSamples(const uint32_t i) {
void Implementation::setNumberofDigitalSamples(const uint32_t i) {
if (numberOfDigitalSamples != i) {
numberOfDigitalSamples = i;
ctbAnalogDataBytes = generalData->setImageSize(
adcEnableMask, numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable ? adcEnableMaskTenGiga : adcEnableMaskOneGiga,
numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable, readoutType);
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
FILE_LOG(logINFO) << "Number of Digital Samples: "
<< numberOfDigitalSamples;
FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame);
return OK;
}
int Implementation::getNumberofCounters() const {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
return numberOfCounters;
}
void Implementation::setNumberofCounters(const int i) {
if (numberOfCounters != i) {
numberOfCounters = i;
if (myDetectorType == MYTHEN3) {
generalData->SetNumberofCounters(i, dynamicRange);
// to update npixelsx, npixelsy in file writer
for (const auto &it : dataProcessor)
it->SetPixelDimension();
SetupFifoStructure();
}
}
FILE_LOG(logINFO) << "Number of Counters: " << numberOfCounters;
}
uint32_t Implementation::getDynamicRange() const {
@ -1354,23 +1313,23 @@ uint32_t Implementation::getDynamicRange() const {
return dynamicRange;
}
int Implementation::setDynamicRange(const uint32_t i) {
void Implementation::setDynamicRange(const uint32_t i) {
if (dynamicRange != i) {
dynamicRange = i;
if (myDetectorType == EIGER) {
if (myDetectorType == EIGER || myDetectorType == MYTHEN3) {
generalData->SetDynamicRange(i, tengigaEnable);
generalData->SetGapPixelsEnable(gapPixelsEnable, dynamicRange, quadEnable);
if (myDetectorType == EIGER) {
generalData->SetGapPixelsEnable(gapPixelsEnable, dynamicRange, quadEnable);
}
// to update npixelsx, npixelsy in file writer
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
}
FILE_LOG(logINFO) << "Dynamic Range: " << dynamicRange;
return OK;
}
slsDetectorDefs::ROI Implementation::getROI() const {
@ -1378,7 +1337,7 @@ slsDetectorDefs::ROI Implementation::getROI() const {
return roi;
}
int Implementation::setROI(slsDetectorDefs::ROI arg) {
void Implementation::setROI(slsDetectorDefs::ROI arg) {
if (roi.xmin != arg.xmin || roi.xmax != arg.xmax) {
roi.xmin = arg.xmin;
roi.xmax = arg.xmax;
@ -1388,14 +1347,12 @@ int Implementation::setROI(slsDetectorDefs::ROI arg) {
framesPerFile = generalData->maxFramesPerFile;
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
FILE_LOG(logINFO) << "ROI: [" << roi.xmin << ", " << roi.xmax << "]";;
FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame);
return OK;
}
bool Implementation::getTenGigaEnable() const {
@ -1403,7 +1360,7 @@ bool Implementation::getTenGigaEnable() const {
return tengigaEnable;
}
int Implementation::setTenGigaEnable(const bool b) {
void Implementation::setTenGigaEnable(const bool b) {
if (tengigaEnable != b) {
tengigaEnable = b;
// side effects
@ -1415,20 +1372,19 @@ int Implementation::setTenGigaEnable(const bool b) {
case MOENCH:
case CHIPTESTBOARD:
ctbAnalogDataBytes = generalData->setImageSize(
adcEnableMask, numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable ? adcEnableMaskTenGiga : adcEnableMaskOneGiga,
numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable, readoutType);
break;
default:
break;
}
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
FILE_LOG(logINFO) << "Ten Giga: " << (tengigaEnable ? "enabled" : "disabled");
FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame);
return OK;
}
int Implementation::getFlippedDataX() const {
@ -1460,7 +1416,7 @@ bool Implementation::getGapPixelsEnable() const {
return gapPixelsEnable;
}
int Implementation::setGapPixelsEnable(const bool b) {
void Implementation::setGapPixelsEnable(const bool b) {
if (gapPixelsEnable != b) {
gapPixelsEnable = b;
@ -1468,11 +1424,9 @@ int Implementation::setGapPixelsEnable(const bool b) {
generalData->SetGapPixelsEnable(b, dynamicRange, quadEnable);
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
FILE_LOG(logINFO) << "Gap Pixels Enable: " << gapPixelsEnable;
return OK;
}
bool Implementation::getQuad() const {
@ -1480,7 +1434,7 @@ bool Implementation::getQuad() const {
return quadEnable;
}
int Implementation::setQuad(const bool b) {
void Implementation::setQuad(const bool b) {
if (quadEnable != b) {
quadEnable = b;
@ -1488,8 +1442,7 @@ int Implementation::setQuad(const bool b) {
// to update npixelsx, npixelsy in file writer
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
if (!quadEnable) {
for (const auto &it : dataStreamer) {
@ -1508,7 +1461,6 @@ int Implementation::setQuad(const bool b) {
}
}
FILE_LOG(logINFO) << "Quad Enable: " << quadEnable;
return OK;
}
bool Implementation::getActivate() const {
@ -1552,50 +1504,73 @@ Implementation::getReadoutMode() const {
return readoutType;
}
int Implementation::setReadoutMode(const readoutMode f) {
void Implementation::setReadoutMode(const readoutMode f) {
if (readoutType != f) {
readoutType = f;
// side effects
ctbAnalogDataBytes = generalData->setImageSize(
adcEnableMask, numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable ? adcEnableMaskTenGiga : adcEnableMaskOneGiga,
numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable, readoutType);
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
FILE_LOG(logINFO) << "Readout Mode: " << sls::ToString(f);
FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame);
return OK;
}
uint32_t Implementation::getADCEnableMask() const {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
return adcEnableMask;
return adcEnableMaskOneGiga;
}
int Implementation::setADCEnableMask(uint32_t mask) {
if (adcEnableMask != mask) {
adcEnableMask = mask;
void Implementation::setADCEnableMask(uint32_t mask) {
if (adcEnableMaskOneGiga != mask) {
adcEnableMaskOneGiga = mask;
ctbAnalogDataBytes = generalData->setImageSize(
mask, numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable ? adcEnableMaskTenGiga : adcEnableMaskOneGiga,
numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable, readoutType);
for (const auto &it : dataProcessor)
it->SetPixelDimension();
if (SetupFifoStructure() == FAIL)
return FAIL;
SetupFifoStructure();
}
FILE_LOG(logINFO) << "ADC Enable Mask: 0x" << std::hex << adcEnableMask
FILE_LOG(logINFO) << "ADC Enable Mask for 1Gb mode: 0x" << std::hex << adcEnableMaskOneGiga
<< std::dec;
FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame);
}
uint32_t Implementation::getTenGigaADCEnableMask() const {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
return adcEnableMaskTenGiga;
}
void Implementation::setTenGigaADCEnableMask(uint32_t mask) {
if (adcEnableMaskTenGiga != mask) {
adcEnableMaskTenGiga = mask;
ctbAnalogDataBytes = generalData->setImageSize(
tengigaEnable ? adcEnableMaskTenGiga : adcEnableMaskOneGiga,
numberOfAnalogSamples, numberOfDigitalSamples,
tengigaEnable, readoutType);
for (const auto &it : dataProcessor)
it->SetPixelDimension();
SetupFifoStructure();
}
FILE_LOG(logINFO) << "ADC Enable Mask for 10Gb mode: 0x" << std::hex << adcEnableMaskTenGiga
<< std::dec;
FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame);
return OK;
}
std::vector<int> Implementation::getDbitList() const {

View File

@ -24,7 +24,7 @@ Listener::Listener(int ind, detectorType dtype, Fifo* f, std::atomic<runStatus>*
uint32_t* portno, std::string* e, uint64_t* nf, uint32_t* dr,
int64_t* us, int64_t* as, uint32_t* fpf,
frameDiscardPolicy* fdp, bool* act, bool* depaden, bool* sm) :
ThreadObject(ind),
ThreadObject(ind, TypeName),
runningFlag(0),
generalData(nullptr),
fifo(f),
@ -55,9 +55,6 @@ Listener::Listener(int ind, detectorType dtype, Fifo* f, std::atomic<runStatus>*
numFramesStatistic(0),
oddStartingPacket(true)
{
if(ThreadObject::CreateThread() == FAIL)
throw sls::RuntimeError("Could not create listener thread");
FILE_LOG(logDEBUG) << "Listener " << ind << " created";
}
@ -67,15 +64,9 @@ Listener::~Listener() {
sem_post(&semaphore_socket);
sem_destroy(&semaphore_socket);
}
ThreadObject::DestroyThread();
}
/** getters */
std::string Listener::GetType(){
return TypeName;
}
bool Listener::IsRunning() {
return runningFlag;
}
@ -155,19 +146,10 @@ void Listener::SetGeneralData(GeneralData* g) {
}
int Listener::SetThreadPriority(int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(thread, SCHED_FIFO, &param) == EPERM)
return FAIL;
FILE_LOG(logINFO) << "Listener Thread Priority set to " << priority;
return OK;
}
int Listener::CreateUDPSockets() {
void Listener::CreateUDPSockets() {
if (!(*activated)) {
return OK;
return;
}
//if eth is mistaken with ip address
@ -186,8 +168,7 @@ int Listener::CreateUDPSockets() {
*udpSocketBufferSize);
FILE_LOG(logINFO) << index << ": UDP port opened at port " << *udpPortNumber;
} catch (...) {
FILE_LOG(logERROR) << "Could not create UDP socket on port " << *udpPortNumber;
return FAIL;
throw sls::RuntimeError("Could not create UDP socket on port "+ std::to_string(*udpPortNumber));
}
udpSocketAlive = true;
@ -195,8 +176,6 @@ int Listener::CreateUDPSockets() {
// doubled due to kernel bookkeeping (could also be less due to permissions)
*actualUDPSocketBufferSize = udpSocket->getActualUDPSocketBufferSize();
return OK;
}
@ -216,12 +195,12 @@ void Listener::ShutDownUDPSocket() {
}
int Listener::CreateDummySocketForUDPSocketBufferSize(int64_t s) {
void Listener::CreateDummySocketForUDPSocketBufferSize(int64_t s) {
FILE_LOG(logINFO) << "Testing UDP Socket Buffer size " << s << " with test port " << *udpPortNumber;
if (!(*activated)) {
*actualUDPSocketBufferSize = (s*2);
return OK;
return;
}
int64_t temp = *udpSocketBufferSize;
@ -247,12 +226,8 @@ int Listener::CreateDummySocketForUDPSocketBufferSize(int64_t s) {
}
} catch (...) {
FILE_LOG(logERROR) << "Could not create a test UDP socket on port " << *udpPortNumber;
return FAIL;
throw sls::RuntimeError("Could not create a test UDP socket on port " + std::to_string(*udpPortNumber));
}
return OK;
}
void Listener::SetHardCodedPosition(uint16_t r, uint16_t c) {

View File

@ -6,103 +6,71 @@
#include "ThreadObject.h"
#include "container_utils.h"
#include <iostream>
#include <syscall.h>
ThreadObject::ThreadObject(int ind):
index(ind),
alive(false),
killThread(false),
thread(0)
{
PrintMembers();
ThreadObject::ThreadObject(int threadIndex, std::string threadType)
: index(threadIndex), type(threadType) {
FILE_LOG(logDEBUG) << type << " thread created: " << index;
sem_init(&semaphore,1,0);
try {
threadObject = sls::make_unique<std::thread>(&ThreadObject::RunningThread, this);
} catch (...) {
throw sls::RuntimeError("Could not create " + type + " thread with index " + std::to_string(index));
}
}
ThreadObject::~ThreadObject() {
DestroyThread();
}
killThread = true;
sem_post(&semaphore);
threadObject->join();
void ThreadObject::PrintMembers() {
FILE_LOG(logDEBUG) << "Index : " << index
<< "\nalive: " << alive
<< "\nkillThread: " << killThread
<< "\npthread: " << thread;
}
void ThreadObject::DestroyThread() {
if(alive){
killThread = true;
sem_post(&semaphore);
pthread_join(thread,nullptr);
sem_destroy(&semaphore);
killThread = false;
alive = false;
FILE_LOG(logDEBUG) << GetType() << " thread with index " << index << " destroyed successfully.";
}
}
int ThreadObject::CreateThread() {
if(alive){
FILE_LOG(logERROR) << "Cannot create thread " << index << ". Already alive";
return FAIL;
}
sem_init(&semaphore,1,0);
killThread = false;
if(pthread_create(&thread, nullptr,StartThread, (void*) this)){
FILE_LOG(logERROR) << "Could not create " << GetType() << " thread with index " << index;
return FAIL;
}
alive = true;
FILE_LOG(logDEBUG) << GetType() << " thread " << index << " created successfully.";
return OK;
}
void* ThreadObject::StartThread(void* thisPointer) {
((ThreadObject*)thisPointer)->RunningThread();
return thisPointer;
sem_destroy(&semaphore);
}
void ThreadObject::RunningThread() {
FILE_LOG(logINFOBLUE) << "Created [ " << GetType() << "Thread " << index << ", "
"Tid: " << syscall(SYS_gettid) << "]";
FILE_LOG(logINFOBLUE) << "Created [ " << type << "Thread " << index << ", Tid: " << syscall(SYS_gettid) << "]";
FILE_LOG(logDEBUG) << type << " thread " << index << " created successfully.";
while(true) {
while(IsRunning()) {
ThreadExecution();
}//end of inner loop
}
//wait till the next acquisition
sem_wait(&semaphore);
if(killThread) {
FILE_LOG(logINFOBLUE) << "Exiting [ " << GetType() <<
" Thread " << index << ", Tid: " << syscall(SYS_gettid) << "]";
pthread_exit(nullptr);
break;
}
}//end of outer loop
}
FILE_LOG(logDEBUG) << type << " thread with index " << index << " destroyed successfully.";
FILE_LOG(logINFOBLUE) << "Exiting [ " << type << " Thread " << index << ", Tid: " << syscall(SYS_gettid) << "]";
}
void ThreadObject::Continue() {
sem_post(&semaphore);
}
void ThreadObject::SetThreadPriority(int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(threadObject->native_handle(), SCHED_FIFO, &param) == EPERM) {
if (!index) {
FILE_LOG(logWARNING) << "Could not prioritize " << type << " thread. "
"(No Root Privileges?)";
}
} else {
FILE_LOG(logINFO) << "Priorities set - " << type << ": " << priority;
}
}

View File

@ -9,9 +9,9 @@
#include "TimeHelper.h"
#include "TypeTraits.h"
#include "sls_detector_defs.h"
#include "sls_detector_exceptions.h"
#include "string_utils.h"
#include "sls_detector_defs.h"
#include <chrono>
#include <iomanip>
#include <sstream>

View File

@ -10,15 +10,15 @@
#include "ansi.h"
#include "sls_detector_exceptions.h"
#include <iostream>
#include <zmq.h>
#include <errno.h>
#include <netdb.h> //gethostbyname()
#include <arpa/inet.h> //inet_ntoa
#include <errno.h>
#include <iostream>
#include <netdb.h> //gethostbyname()
#include <rapidjson/document.h> //json header in zmq stream
#include <string.h>
#include <unistd.h> //usleep in some machines
#include <vector>
#include <zmq.h>
using namespace rapidjson;

View File

@ -3,9 +3,9 @@
#include "sls_detector_defs.h"
#include <string>
#include <cstdio>
#include <fstream>
#include <stdio.h>
#include <string>
/** (used by multi and sls)

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