Compare commits

..

187 Commits

Author SHA1 Message Date
da8e0060d3 updated release notes and project version 2022-01-04 10:44:07 +01:00
85da65ca15 update versioning (prev commit) 2022-01-04 10:38:45 +01:00
4fe067363a This commit fixes the issue #336
A delay of 100ms has been added between the generation of the stop pulse and the resetCore function call. This should give enough time to the detector to readout and streamout the ongoing frame before the internal logic is reset (even after the transmission is delayed with txndelay_frame).

Conflicts:
	slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServerv6.1.0
2022-01-04 10:37:57 +01:00
066706872d updated version and added python 3.10 build 2021-11-26 09:25:41 +01:00
f98c403f06 Merge branch 'main' into developer 2021-11-25 13:03:03 +01:00
5dcc2ab35c fixed server names versioing 2021-11-25 13:01:23 +01:00
d80c5e1c02 fixed versions in servers 2021-11-25 12:59:44 +01:00
7acc201797 fix release version 2021-11-25 12:56:21 +01:00
57a52ba2dc update release version 2021-11-25 12:55:47 +01:00
c011129c43 Merge branch 'main' into 6.0.1.rc1 2021-11-25 12:40:24 +01:00
2ed8b85143 update release notes 2021-11-25 12:30:59 +01:00
5ac2fc33ff release notes 2021-11-25 12:29:45 +01:00
c169e6b896 fixed tests 2021-11-25 12:26:48 +01:00
497d29db39 fix for eiger overwriting of server nchip 2021-11-25 12:21:44 +01:00
2fbf0d6996 to fix test changing order 2021-11-25 12:15:20 +01:00
16246407c5 Merge branch '6.0.1.rc1' of github.com:slsdetectorgroup/slsDetectorPackage into 6.0.1.rc1 2021-11-25 12:09:16 +01:00
4a89bef87b no need to update server nchan/nchip/ndac values from client 2021-11-25 12:09:07 +01:00
a146257b13 testing 2021-11-25 11:30:14 +01:00
340b18ca83 Merge branch '6.0.1.rc1' of github.com:slsdetectorgroup/slsDetectorPackage into 6.0.1.rc1 2021-11-25 11:25:24 +01:00
271f6da92e tests fix 2021-11-25 11:25:18 +01:00
9d20bf25c6 fix tests 2021-11-25 10:51:59 +01:00
6668fef61a fix test 2021-11-25 10:42:13 +01:00
a455a95aab fix tests 2021-11-25 10:31:19 +01:00
7f7a691b25 fix test 2021-11-25 10:19:48 +01:00
7536971b34 binaries in 2021-11-25 10:16:37 +01:00
8ca11ec705 Merge branch '6.0.1.rc1' of github.com:slsdetectorgroup/slsDetectorPackage into 6.0.1.rc1 2021-11-25 10:15:02 +01:00
00d63e48bb fix tests 2021-11-25 10:14:49 +01:00
146da0f20f binaries in 2021-11-25 10:02:14 +01:00
993ba5926e update test fix 2021-11-25 10:00:40 +01:00
44424bcbe3 fix 2021-11-25 09:36:50 +01:00
3570795469 fix test 2021-11-25 09:34:00 +01:00
a9d61526ef flip rows only for hw2.0 for jungfrau 2021-11-25 09:30:04 +01:00
2a5116f49a rename binary 2021-11-25 09:18:23 +01:00
5e0408474d binaries in 2021-11-25 09:17:01 +01:00
e7b11f3eb1 fix tets 2021-11-25 08:54:01 +01:00
c1e374ed51 Merge branch '6.0.1.rc1' of github.com:slsdetectorgroup/slsDetectorPackage into 6.0.1.rc1 2021-11-25 08:42:46 +01:00
eb690437c9 fix tests: get filtercells only for chipv1.1 2021-11-25 08:42:39 +01:00
f076c1cbb7 missing ( 2021-11-24 18:03:26 +01:00
de9854e773 fix message for lto and get/put target 2021-11-24 17:59:22 +01:00
150d8f5fda Merge pull request #335 from slsdetectorgroup/ltofix
Adding LTO to tests and disable them for Debug builds
2021-11-24 17:53:09 +01:00
b0a5a76065 adding LTO to tests 2021-11-24 17:40:14 +01:00
77e610f5a5 fixing tests to run on rhel7 2021-11-24 17:14:20 +01:00
0689c82e98 troubleshooting docs 2021-11-24 17:11:17 +01:00
ce94364c73 binary 2021-11-24 17:00:08 +01:00
1ed10acc01 g2 speed also requires dbit pipeline to be set 2021-11-24 16:59:20 +01:00
2c57d5f72d release update 2021-11-24 14:53:52 +01:00
0d867c91d9 release doc 2021-11-24 14:50:17 +01:00
845920f8cc renaming 2021-11-24 14:49:14 +01:00
eff4ba01b9 jungfrau: flip rows and partial readout only available for hw2.0 2021-11-24 14:44:42 +01:00
bcf0922b8d changed server names 2021-11-24 11:40:20 +01:00
d689c415e4 binaries in 2021-11-24 11:34:35 +01:00
e9caa53af0 minor text fix + macro define in the right place 2021-11-24 11:32:19 +01:00
81eb0217ad fixing the error messagE 2021-11-24 10:19:35 +01:00
0e23665de5 binaries in 2021-11-24 09:27:53 +01:00
044843c8b7 check not required when writing to fpga flash dir 2021-11-24 09:27:18 +01:00
9d63875802 binaries in 2021-11-23 16:27:29 +01:00
9aea183f5c typo 2021-11-23 16:26:56 +01:00
f39f93b2c8 adding the check for copydetector server and updatemode (also for any kind of updatedetectorserver, programfpga and updatekernel) 2021-11-23 16:25:28 +01:00
ed2e6e4e28 print error 2021-11-23 15:45:01 +01:00
74348afcf6 fix 2021-11-23 15:30:08 +01:00
a101e18d60 fix to ensure updatekernel does not work with Amd blackfin flash and a kernel older than the current one 2021-11-23 15:23:16 +01:00
d9686e0b6a minor 2021-11-22 16:30:33 +01:00
5f38165b07 binaries in 2021-11-22 15:15:00 +01:00
9d859cb4c2 fixed warnings in server for format 2021-11-22 15:14:26 +01:00
7772eb153d using const for getupdatemode 2021-11-22 15:08:58 +01:00
e37725ac12 release notes and some fixes 2021-11-22 14:02:54 +01:00
f3c95148a7 LGTM. updated versioning and server versioning 2021-11-22 13:06:59 +01:00
b9b3055984 updated release notes 2021-11-19 18:52:53 +01:00
464ebe70f1 bug fix: servername interchanged for firmware name 2021-11-19 08:53:07 +01:00
4f76219456 Merge pull request #334 from slsdetectorgroup/4updatemode
4updatemode
2021-11-18 16:42:53 +01:00
18b0e84fbf eiger cant reboot 2021-11-18 15:55:12 +01:00
1c6e33064b minor typo 2021-11-18 15:39:34 +01:00
a74f71be0e binaries in 2021-11-18 15:39:05 +01:00
848884f6cf temp server binary in tmp folder already has full path 2021-11-18 15:33:47 +01:00
4690bd0b19 binaries in 2021-11-17 10:14:35 +01:00
f7286d29fa merge fix 2021-11-17 10:13:44 +01:00
eb666d8b05 Merge pull request #333 from slsdetectorgroup/3kernelupdate
3kernelupdate
2021-11-17 10:10:19 +01:00
148c979727 binaries in 2021-11-17 09:26:56 +01:00
00775b543e fixed warnings 2021-11-17 09:25:36 +01:00
904af4de06 fix to allowing update mode functions in update mode and removing exception about set_position for hostname in update mode 2021-11-16 09:55:29 +01:00
eb69d7cb69 update mode added. need to fix why udpatemode get and set not in allowed functions 2021-11-12 17:18:26 +01:00
0ffd30e147 works virutally for virtual servers 2021-11-12 15:18:42 +01:00
eda66e63a5 allowed functions in update mode 2021-11-11 19:08:05 +01:00
6e276770eb binaries in 2021-11-11 11:05:59 +01:00
4fb19ceaa5 minor 2021-11-11 11:01:19 +01:00
1840ad218a complete path for eiger 2021-11-11 11:00:31 +01:00
93a191f122 complete path for eiger 2021-11-11 10:56:09 +01:00
c532ecc2e8 moved movefile and writefile to common and avoiding need to send different named files for nios 2021-11-11 10:43:17 +01:00
25eecf7039 siable warning to truncate and compile fix 2021-11-11 10:12:08 +01:00
85d350b48b blackfin server is not in memory 2021-11-11 10:06:47 +01:00
ec1ee635d5 works and allowed reboot 2021-11-11 09:38:01 +01:00
18bbce70b1 fwrite bug 2021-11-11 09:36:15 +01:00
fa822634aa copying binary not done properly 2021-11-11 09:30:53 +01:00
93a86324fb typo bug fix 2021-11-11 09:25:28 +01:00
9d21062f5a remove reboot for checks 2021-11-11 09:24:48 +01:00
a099637b7e checksum also for nios 2021-11-11 09:23:24 +01:00
4dfdd6f10b minor 2021-11-11 09:22:15 +01:00
4f6640a6f1 minor 2021-11-11 09:21:21 +01:00
65a2a9eb06 checksum of server binary file 2021-11-11 09:12:14 +01:00
169361d459 blackfin requires a few writes 2021-11-10 18:54:02 +01:00
0144eff60b binaries in 2021-11-10 17:54:34 +01:00
4f5f8408cf more error detail 2021-11-10 17:53:40 +01:00
32d664a77d actually writing the server binary from memory to file before linking, sycing, permissions etc 2021-11-10 17:48:18 +01:00
4a8c365447 typo 2021-11-10 17:25:37 +01:00
4b46091be2 python fix, server copy wrong filename 2021-11-10 16:40:14 +01:00
5190e2ab30 refactoring 2021-11-10 15:56:01 +01:00
adc6cf214a fixed runtime error with module::sendprogram default servername value 2021-11-10 14:54:42 +01:00
fb7daf426f binaries in 2021-11-10 14:04:16 +01:00
0e9c88dfa2 programfpga already does reboot 2021-11-10 11:49:32 +01:00
233d374a4d server works 2021-11-10 11:47:26 +01:00
15aa42d328 wip 2021-11-10 10:58:29 +01:00
14ee2087dc rebootcontroller after updating kernel 2021-11-09 16:19:53 +01:00
1e134276ca typo 2021-11-09 16:06:37 +01:00
d9168803ae nios kernel update takes time, simulating 2021-11-09 16:05:47 +01:00
0090c183bf more print and fclose 2021-11-09 16:00:01 +01:00
f5d62b50ce allowing kernel update for nios 2021-11-09 15:53:31 +01:00
098601e717 need to find a better way to show unrecognixed functions 2021-11-09 15:52:37 +01:00
898ee9b7b7 arguments stays for unknown enum 2021-11-09 15:41:59 +01:00
1fd15fadf8 Merge branch '3kernelupdate' of github.com:slsdetectorgroup/slsDetectorPackage into 3kernelupdate 2021-11-09 15:37:20 +01:00
db88f67cda unknown function enum error proper print 2021-11-09 15:37:12 +01:00
0f08ddd454 binaries in 2021-11-09 14:41:00 +01:00
f8e2522a11 minor 2021-11-09 14:40:36 +01:00
5143295711 binaries in 2021-11-09 14:36:24 +01:00
a59537088b fix 2021-11-09 14:35:49 +01:00
dde98fc8b6 fix 2021-11-09 14:33:24 +01:00
c0e3bbbc61 Merge branch '3kernelupdate' of github.com:slsdetectorgroup/slsDetectorPackage into 3kernelupdate 2021-11-09 14:10:24 +01:00
bf778b5336 too much read from kernel flash for checksum validation 2021-11-09 14:10:15 +01:00
99c44b2592 binaries in 2021-11-09 11:48:56 +01:00
6569e4a8bf kernel update fix 2021-11-09 11:46:27 +01:00
3ebfbb123d binaries in 2021-11-09 11:44:38 +01:00
8d2bb3d678 Merge branch '3kernelupdate' of github.com:slsdetectorgroup/slsDetectorPackage into 3kernelupdate 2021-11-09 11:42:35 +01:00
e81e06696a kernel update works, but without flash checksum 2021-11-09 11:42:26 +01:00
99ad1d9228 binaries in 2021-11-09 10:35:42 +01:00
33c86db019 gpio defined checks 2021-11-09 10:35:18 +01:00
f085b4ca1e binaries in 2021-11-09 10:22:44 +01:00
7558c43b8c reverting last change 2021-11-09 10:22:24 +01:00
e332439020 binaries in 2021-11-09 10:20:20 +01:00
ea44151cb1 Merge branch '3kernelupdate' of github.com:slsdetectorgroup/slsDetectorPackage into 3kernelupdate 2021-11-09 10:19:53 +01:00
3167aade45 more print for error in basictests 2021-11-09 10:19:43 +01:00
44709b1384 binaries in 2021-11-09 10:09:19 +01:00
717d68c217 bug fix, not returning 2021-11-09 10:08:57 +01:00
c218d7dc00 bug fix, kernel index 2021-11-09 10:02:47 +01:00
30d38ecae9 print error even if in execute 2021-11-09 09:56:13 +01:00
254b918408 binaries in 2021-11-09 09:51:02 +01:00
1506c70329 bugfix 2021-11-09 09:50:40 +01:00
729441dcc6 Merge branch '3kernelupdate' of github.com:slsdetectorgroup/slsDetectorPackage into 3kernelupdate 2021-11-09 09:49:30 +01:00
90b9b57865 bugfix 2021-11-09 09:49:21 +01:00
29a41c6b19 binaries in 2021-11-09 09:23:04 +01:00
64a25a242b server side fixed 2021-11-08 17:24:51 +01:00
7b4f8c118b client done 2021-11-08 14:26:53 +01:00
54ee4ec653 Merge branch 'developer' into 3kernelupdate 2021-11-08 09:40:07 +01:00
59bcf6a0d0 Merge pull request #331 from slsdetectorgroup/2kernelversion
2kernelversion
2021-11-08 09:39:24 +01:00
6462a7162e wip 2021-11-05 17:01:45 +01:00
e15028e94c Merge branch 'developer' into 3kernelupdate 2021-11-05 12:31:36 +01:00
81e1221e0d Merge branch 'developer' into 2kernelversion 2021-11-05 12:28:37 +01:00
953fc9bb48 Merge pull request #332 from slsdetectorgroup/pyfix
removed c++14 only overload_cast from pybind enum interface
2021-11-05 12:28:10 +01:00
91cf18c5d1 removed comment 2021-11-05 12:03:01 +01:00
642989cab2 removed c++14 only overload_cast from pybind enum interface 2021-11-05 11:56:57 +01:00
d438b53c68 wip 2021-11-04 19:18:10 +01:00
6e49b77b08 updating kernel like program fpga, execute command to print which module failed, unlinking temporary file while programming bug fix 2021-11-03 17:17:24 +01:00
5f94ca30f1 removed deprecated root include 2021-11-03 16:26:59 +01:00
98cf908918 Merge branch 'developer' into 2kernelversion 2021-11-03 14:44:49 +01:00
cb39a59508 fixes for kernelversion 2021-11-03 14:42:14 +01:00
b68ef6cbd0 binaries in 2021-11-03 11:47:14 +01:00
eff64f99f2 addd kernel version 2021-11-03 11:46:46 +01:00
2b1028d636 Merge pull request #330 from slsdetectorgroup/programfix
Program firmware for new kernel
2021-11-03 11:43:37 +01:00
1da2761654 bug fix 2021-11-03 10:49:59 +01:00
7c2e64d9fe rleease notes 2021-11-02 17:21:27 +01:00
340d708b12 updated m3 kernel version 2021-11-02 17:07:55 +01:00
3f517420af updated kernel date for gotthard2, checking kernel code similar for blackfin and nios, need to add date for m3 2021-11-02 16:59:54 +01:00
05c9fcfe19 gpio3 only when new kernel 2021-11-02 14:23:14 +01:00
dcae1b7a2b bianries in 2021-10-29 17:16:22 +02:00
d8570bc9a9 updated date kernel 2021-10-29 17:14:26 +02:00
e3bfdaf38e binaries in 2021-10-29 16:45:18 +02:00
5188e600a2 specific kernel version name 2021-10-29 16:45:05 +02:00
45b3514118 moved verifykernelversion to common 2021-10-29 16:43:48 +02:00
2813cd5ac2 remove cest as strptime doesnt work on bfin with timezone 2021-10-29 16:28:58 +02:00
2d2287e189 check kernel version before enabling the gipo 3 chipenable pins 2021-10-29 12:25:30 +02:00
c3eff0246a programing problem fixed 2021-10-28 15:51:29 +02:00
c911fe4c85 bash script for cmk.sh in ubuntu 2021-10-28 14:18:58 +02:00
87a515a549 Merge pull request #329 from slsdetectorgroup/rxhostnamenone
Bug: rxhostname none
2021-10-27 14:36:16 +02:00
0b2d294a19 updated release notes 2021-10-27 14:27:34 +02:00
b62a6eff64 updated release notes 2021-10-27 14:27:08 +02:00
dde62f13d5 fixed bug. setting rx_hostname to none should not throw 2021-10-27 11:29:01 +02:00
146b012eff minor changes 2021-10-27 11:14:29 +02:00
95897085ec missed serverBin 2021-10-27 11:02:28 +02:00
e53a71f88f updated to developer versioning 2021-10-27 11:00:01 +02:00
102 changed files with 3041 additions and 1943 deletions

View File

@ -1,12 +1,12 @@
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
cmake_minimum_required(VERSION 3.9)
cmake_minimum_required(VERSION 3.12)
project(slsDetectorPackage)
set(PROJECT_VERSION 6.0.0)
set(PROJECT_VERSION 6.1.1)
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
# cmake_policy(SET CMP0074 NEW)
cmake_policy(SET CMP0074 NEW)
include(cmake/project_version.cmake)
#functions to add compiler flags
@ -67,10 +67,7 @@ set(ClangFormat_EXCLUDE_PATTERNS "build/"
${CMAKE_BINARY_DIR})
find_package(ClangFormat)
#Enable LTO if available
include(CheckIPOSupported)
check_ipo_supported(RESULT SLS_LTO_AVAILABLE)
message(STATUS "SLS_LTO_AVAILABLE:" ${SLS_LTO_AVAILABLE})
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@ -81,6 +78,16 @@ if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
endif()
#Enable LTO if available
include(CheckIPOSupported)
check_ipo_supported(RESULT SLS_LTO_AVAILABLE)
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
message(STATUS "Building with link time optimization")
else()
message(STATUS "Building without link time optimization")
endif()
#Add two fake libraries to manage options
add_library(slsProjectOptions INTERFACE)
add_library(slsProjectWarnings INTERFACE)
@ -133,11 +140,10 @@ endif()
# Add or disable warnings depending on if the compiler supports them
# The function checks internally and sets HAS_warning-name
# sls_enable_cxx_warning("-Wnull-dereference")
# sls_enable_cxx_warning("-Wduplicated-cond")
# sls_disable_cxx_warning("-Wclass-memaccess")
# sls_disable_c_warning("-Wstringop-truncation")
# sls_disable_c_warning("-Wformat-nonliteral")
sls_enable_cxx_warning("-Wnull-dereference")
sls_enable_cxx_warning("-Wduplicated-cond")
sls_disable_cxx_warning("-Wclass-memaccess")
sls_disable_c_warning("-Wstringop-truncation")
if(SLS_USE_SANITIZER)
@ -172,35 +178,35 @@ set(CMAKE_INSTALL_RPATH $ORIGIN)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
# set(ZeroMQ_HINT "" CACHE STRING "Hint where ZeroMQ could be found")
# #Adapted from: https://github.com/zeromq/cppzmq/
# if (NOT TARGET libzmq)
# if(ZeroMQ_HINT)
# message(STATUS "Looking for ZeroMQ in: ${ZeroMQ_HINT}")
# find_package(ZeroMQ 4
# NO_DEFAULT_PATH
# HINTS ${ZeroMQ_DIR}
# )
# else()
# find_package(ZeroMQ 4 QUIET)
# endif()
set(ZeroMQ_HINT "" CACHE STRING "Hint where ZeroMQ could be found")
#Adapted from: https://github.com/zeromq/cppzmq/
if (NOT TARGET libzmq)
if(ZeroMQ_HINT)
message(STATUS "Looking for ZeroMQ in: ${ZeroMQ_HINT}")
find_package(ZeroMQ 4
NO_DEFAULT_PATH
HINTS ${ZeroMQ_DIR}
)
else()
find_package(ZeroMQ 4 QUIET)
endif()
# # libzmq autotools install: fallback to pkg-config
# if(NOT ZeroMQ_FOUND)
# message(STATUS "CMake libzmq package not found, trying again with pkg-config (normal install of zeromq)")
# list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/libzmq-pkg-config)
# find_package(ZeroMQ 4 REQUIRED)
# endif()
# libzmq autotools install: fallback to pkg-config
if(NOT ZeroMQ_FOUND)
message(STATUS "CMake libzmq package not found, trying again with pkg-config (normal install of zeromq)")
list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/libzmq-pkg-config)
find_package(ZeroMQ 4 REQUIRED)
endif()
# # TODO "REQUIRED" above should already cause a fatal failure if not found, but this doesn't seem to work
# if(NOT ZeroMQ_FOUND)
# message(FATAL_ERROR "ZeroMQ was not found, neither as a CMake package nor via pkg-config")
# endif()
# TODO "REQUIRED" above should already cause a fatal failure if not found, but this doesn't seem to work
if(NOT ZeroMQ_FOUND)
message(FATAL_ERROR "ZeroMQ was not found, neither as a CMake package nor via pkg-config")
endif()
# if (ZeroMQ_FOUND AND NOT TARGET libzmq)
# message(FATAL_ERROR "ZeroMQ version not supported!")
# endif()
# endif()
if (ZeroMQ_FOUND AND NOT TARGET libzmq)
message(FATAL_ERROR "ZeroMQ version not supported!")
endif()
endif()
if (SLS_USE_TESTS)
enable_testing()

View File

@ -1,298 +1,39 @@
SLS Detector Package 6.0.0 released on 21.10.2021
==================================================
SLS Detector Package Minor Release 6.1.1 released on 04.01.2022
===============================================================
This document describes the differences between v6.0.0 and v5.1.0.
This document describes the differences between v6.1.1 and v6.1.0.
CONTENTS
--------
1. New or Changed Features
2. Resolved Issues
3. Known Issues
4. Changes in Next Major Release
5. Firmware Requirements
6. Download, Documentation & Support
1. Resolved Issues
2. Firmware Requirements
3. Kernel Requirements
4. Download, Documentation & Support
1. New or Changed Features
==========================
Added License. Read COPYING for more details.
Client
------
1. Shared libraries
They are versioned from this release on (6.0.0).
2. [Jungfrau] Chip version
Features for chipv1.1 incorporated
Command line: chipversion, API: getchipVersion
gets chip version (1.0 or 1.1)
chipv1.1 requires config_jungfrau.txt on detector server and HW 2.0.
3. [Jungfrau] Chip configuration (only chipv1.1)
powering on the chip and changing settings will configure the chip.
Hence, required before acquisition.
4. [Jungfrau] Settings and Gain mode
Settings can be gain0 and highgain0. Gain mode can be dynamicgain,
forceswitchg1, forceswitchg2, fixg1, fixg2, fixg0. fixg0 must be
used with EXTRA caution as you can damage the detector.
Changing settings also changes dac values of 3 dacs
(vref_prech, vref_ds and vref_comp) and reconfigures chip (only v1.1)
5. [Jungfrau] Storage cells (only chipv1.1)
Additional number of storage cells not applicable for chipv1.1.
Storage cell start is only allowed from 0 - 3 for chipv1.1
(0 - 15 for chipv1.0).
Command line: extrastoragecells, Previous Command line: storagecells
API: remains the same.
6. [Gotthard2][Jungfrau] Filter Resistor
Command line: filterresistor, API: getFilterResistor/ setFilterResistor
Previous Command: filter, setFilter/ getFilter
Set Filter resistor. Increasing values for increasing resistance.
[Jungfrau] only for chipv1.1. Options: [0|1]. Default is 1.
[Gotthard2] Options: [0|1|2|3]. Default is 0.
7. [Jungfrau] Filter cell (only chipv1.1)
Command line: filtercells, API: getNumberOfFilterCells/ setNumberOfFilterCells
Set filter cell. Options: [0-12]. Advanced user command.
8. [Jungfrau] Comparator disable time (only chipv1.1)
Command line: compdisabletime, API: getComparatorDisableTime/
setComparatorDisableTime
One can customize the period to disable comparator.
9. [Eiger][Jungfrau] Read n rows
Command line: readnrows, API: getReadNRows/ setReadNRows
Previous Command: readnlines, getPartialReadout/ setPartialReadout
[Eiger] same as before
[Jungfrau] Options: 8 - 512, multiples of 8. Default is 512.
10. [Gotthard2][Jungfrau] Current source
Command line: currentsource, API: getCurrentSource, setCurrentSource
Enable or disable current source. Default is disabled.
[Gotthard2] Can only enable or disable.
[Jungfrau] Can choose to fix, select source and choose normal or low
current. Normal/ low only for chipv1.1.
Select source is 0-63 for chipv1.0 and a 64 bit mask for chipv1.1.
11. Default dac
Command line: defaultdac, API: getDefaultDac/ setDefaultDac
change default value of a dac
[Jungfrau][Mythen3] Also change default value of dac for particular
setting.
12. Reset dacs
Command line: resetdacs, API: resetToDefaultDacs
Previous command: defaultdacs
Resets dacs to their default values or hard coded values.
13. [Mythen3] Gain Capacitance
Command line: gaincaps, API: getGainCaps/ setGainCaps
Set various gain capacitances.
14. [Gotthard2] Veto Streaming from chip
Command line: veto, API: getVeto/ setVeto
This command used to mean veto streaming from detector. Now, it means
veto streaming from chip (New feature). Default is disabled.
15. [Gotthard2] Veto streaming from detector
Command line: vetostream, API: getVetoStream, setVetoStream
Options: None, local link interface, 10 10GbE, Both
Default: None
10GbE (as before) will enable 2 udp interfaces in receiver.
16. [Gotthard2] Veto algorithm
Command line: vetoalg, API: getVetoAlgorithm/ setVetoAlgorithm
Set veto algorithm for each interface.
Options: hits, raw
17. [Eiger][Gotthard2][Mythen3] Module ID
Command line: moduleid, API: getModuleId
Previous command (Eiger only): serialnumber, getSerialNumber
Unique id read from txt file on detector and streamed out in udp header.
18. [Gotthard2]
Command line: dbitpipeline, API: getDBITPipeline/ setDBITPipeline
Set pipeline to latch digital bits. Options: 0-7
19. [Eiger][Jungfrau] Round Robin commands
Command line, udp_dstlist, API: getDestinationUDPList/
setDestinationUDPList
Round robin commands at the moment does not configure the receiver.
Set multiple udp destinations in the detector to stream udp data packets
to. Upto 32 destinations. Refer documentation for details.
Command line, udp_numdst, API: getNumberofUDPDestinations
[Jungfrau] Command line, udp_firstdst, API: getFirstUDPDestination/
setFirstUDPDestination
20. Command Line Parsing
Parsing of detector index and module index has been modified to
integrate round robin index.
[detector index]-[module index]:[round robin index] [command]
It is backwards compatible.
For ease, one can also execute
sls_detector_put [module index] [command]
21. Clear Udp Destination
Command line, udp_cleardst, API: clearUDPDestinations
This is useful when changing receivers for a detector or for round robin
system.
22. Shared Memory Naming
Shared memory name has been changed to reflect a more appropriate naming
scheme.
23. [Eiger][Mythen3] Blocking trigger
Command line: blockingtrigger, API: sendSoftwareTrigger
Sends software trigger signal to detector and blocks till frames are
sent out for that trigger.
24. [Eiger] Data stream enable for ports
Command line: datastream, API: getDataStream/ setDataStream
Enable or disable each port. Default: enabled
25. Changing TCP ports
This will only affect shared memory and will not try to change the
current tcp port of the control/stop server in detector.
26. [Eiger][Jungfrau][Gotthard2] Speed
Command line: readoutspeed, readoutspeedlist API: getReadoutSpeed/ setReadoutSpeed /
getReadoutSpeedList
Previous command: speed, setSpeed/ getSpeed
[Eiger][Jungfrau] same as before.
[Gotthard2] New command to set readout speed. Options: 108, 144 (in MHz)
27. [Eiger][Jungfrau] Flip rows
Command line: fliprows, API: getFlipRows/ setFlipRows
Previous command: flippeddatax, setBottom/ getBottom
[Jungfrau] Flips rows in detector only for HW v2.0.
slsReceiver and slsDetectorGui will not flip them again.
[Eiger] same as before.
28. [Jungfrau]
Command line changes: autocompdisable, Previous command line: auto_comp_disable
Detector servers
----------------
1. [Gotthard2] Bad Channels moved to a new register, default settings
including clock frequency changed
2. [Gotthard2] Updated config file in detector server
Virtual servers
----------------
1. Artifical pixel values increasing by every packet, instead of every pixel.
2. All possible features updated.
Receiver
--------
1. Frames caught in metadata
Frames caught by the master receiver is added to master file metadata.
Hdf5 and Binary version numbers changed to 6.3
2. Removed Padding option for Deactivated half modules.
3. Changing Receiver TCP ports
This will only affect shared memory and will not try to change the
current tcp port of the receiver.
Gui
----
1. [Mythen3] counters added in settings tab
2. Resolved Issues
1. Resolved Issues
==================
Detector Servers
----------------
1. [Gotthard2] Tolerance in time parameters.
Eg. 220 ns was being set to 215 ns, instead of 222ns.
2. [Jungfrau] Stopping in trigger mode and then switching to auto timing mode
blocks data streaming from detector. Workaround fix made in
detector server to reset core until next firmware release.
3. [Jungfrau][CTB][Moench][Gotthard][Gotthard2][Mythen3] Firmware Programming
Firmware programming incorporates more validations such as checksum of
program. Always ensure client and server are of same release before
programming firmware.
4. [Eiger] Stop sends last frame
Stop acquisition will now also send out all complete frames in fifo.
5. [Eiger] Bottom not rotated in quad mode. Fixed.
6. [Mythen3] counter mask effect on vthreshold
Setting counter mask changes vth daac values (ie. disabling sets to 2800),
vthreshold only changes for enabled counters, setting vth overwrites
dac even if counter disabled and when counters enabled, remembers set
values.
Detector Server
---------------
7. [Eiger] fast quad fix for loading trimbits
8. [Eiger] Can also use copydetectorserver command.
[All] copydetectorserver command also creates a link to the binary copied
with a shorter name ([detector]DetectorServer only)
Receiver
--------
1. Disabled port or deactivated (half) modules will not create files.
1. [Jungfrau] Cannot start
Under some circumstances and not always reproducible, the detector
cannot start once it has stopped. Fixed by adding a delay between the
stop pulse and the resetting core to give sufficient time to readout and
stream out the ongoing frame.
3. Known Issues
===============
Receiver
--------
1. It does not handle readnrows or partial readout. Only the summary
is adjusted to print in red. However, it will still write complete
images with missing data padded. Roi will be implemented in future
that can be complemented with this feature to remove the additional
data in files.
2. Round robin is not implemented in receiver side, ie. one cannot configure
more than 1 receiver at a time. This will/might be done in the future.
4. Changes in Next Major Release
================================
1. Naming of Package
The package might be renamed and so might the binaries, libraries,
namespace,include paths in the next major release (which is breaking API).
5. Firmware Requirements
2. Firmware Requirements
========================
Note: No change to 6.1.0.
Eiger
=====
Compatible version : 08.10.2021 (v29)
@ -325,7 +66,6 @@ This document describes the differences between v6.0.0 and v5.1.0.
Detector Upgrade
================
The following can be upgraded remotely:
Eiger via bit files
Jungfrau via command <.pof>
@ -344,8 +84,37 @@ This document describes the differences between v6.0.0 and v5.1.0.
3. Kernel Requirements
======================
6. Download, Documentation & Support
Note: No change to 6.1.0.
Blackfin
========
Latest version: Fri Oct 29 00:00:00 2021
Older ones will work, but might have issues with programming firmware via
the package.
Nios
====
Compatible version: Mon May 10 18:00:21 CEST 2021
Kernel Upgrade
==============
Eiger via bit files
Others via command
Commands: udpatekernel, kernelversion
Instructions available at
https://slsdetectorgroup.github.io/devdoc/commandline.html
https://slsdetectorgroup.github.io/devdoc/detector.html
https://slsdetectorgroup.github.io/devdoc/pydetector.html
4. Download, Documentation & Support
====================================
Download

View File

@ -7,9 +7,9 @@ function(enable_cxx_warning flag target)
check_cxx_compiler_flag(${flag} ${flag_name})
if(${flag_name})
target_compile_options(${target} INTERFACE ${flag})
message("Adding: ${flag} to ${target}")
message(STATUS "Adding: ${flag} to ${target}")
else()
message("Flag: ${flag} not supported")
message(STATUS "Flag: ${flag} not supported")
endif()
endfunction()
@ -18,9 +18,9 @@ function(enable_c_warning flag target)
check_c_compiler_flag(${flag} ${flag_name})
if(${flag_name})
target_compile_options(${target} INTERFACE ${flag})
message("Adding: ${flag} to ${target}")
message(STATUS "Adding: ${flag} to ${target}")
else()
message("Flag: ${flag} not supported")
message(STATUS "Flag: ${flag} not supported")
endif()
endfunction()
@ -31,10 +31,10 @@ function(disable_cxx_warning flag target)
if(${flag_name})
string(REPLACE "-W" "-Wno-" neg_flag ${flag})
message("Adding: ${neg_flag} to ${target}")
message(STATUS "Adding: ${neg_flag} to ${target}")
target_compile_options(${target} INTERFACE ${neg_flag})
else()
message("Warning: ${flag} not supported no need to disable")
message(STATUS "Warning: ${flag} not supported no need to disable")
endif()
endfunction()
@ -43,10 +43,10 @@ function(disable_c_warning flag target)
check_c_compiler_flag(${flag} ${flag_name})
if(${flag_name})
string(REPLACE "-W" "-Wno-" neg_flag ${flag})
message("Adding: ${neg_flag} to ${target}")
message(STATUS "Adding: ${neg_flag} to ${target}")
target_compile_options(${target} INTERFACE ${neg_flag})
else()
message("Warning: ${flag} not supported no need to disable")
message(STATUS "Warning: ${flag} not supported no need to disable")
endif()
endfunction()

2
cmk.sh
View File

@ -1,6 +1,6 @@
#!/bin/bash
# SPDX-License-Identifier: LGPL-3.0-or-other
# Copyright (C) 2021 Contributors to the SLS Detector Package
#!/bin/bash
CMAKE="cmake3"
BUILDDIR="build"
INSTALLDIR=""

View File

@ -3,6 +3,7 @@ python:
- 3.7
- 3.8
- 3.9
- 3.10
numpy:
- 1.17
- 1.17

View File

@ -61,7 +61,6 @@ set( HEADERS
#set(ROOT_INCLUDE_PATH ${CMAKE_CURRENT_SOURCE_DIR})
# ROOT dictionary generation
include("${ROOT_DIR}/RootMacros.cmake")
root_generate_dictionary(ctbDict ${HEADERS} LINKDEF ctbLinkDef.h)
add_library(ctbRootLib SHARED ctbDict.cxx)
target_include_directories(ctbRootLib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
@ -86,4 +85,5 @@ target_link_libraries(ctbGui PUBLIC
set_target_properties(ctbGui PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
)

View File

@ -305,43 +305,53 @@ Firmware Troubleshooting with blackfin
5. If one can't list it, read the next section to try to get the blackfin to list it.
How to get back mtd3 drive remotely (copying new kernel)
How to get back mtd3 drive remotely (udpating kernel)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You have 2 alternatives to update the kernel.
.. code-block:: bash
# step 1: get the kernel image (uImage.lzma) from slsdetectorgroup
# and copy it to pc's tftp folder
1. Commands via software (>= v6.0.0)
# step 2: connect to the board
telnet bchipxxx
.. code-block:: bash
#step 3: go to directory for space
cd /var/tmp/
sls_detector_put updatekernel /home/...path-to-kernel-image
# step 3: copy kernel to board
tftp pcxxx -r uImage.lzma -g
# step 4: verify kernel copied properly
ls -lrt
# step 5: erase flash
flash_eraseall /dev/mtd1
# step 6: copy new image to kernel drive
cat uImage.lzma > /dev/mtd1
# step 7:
sync
# step 8:
reboot
# step 9: verification
telnet bchipxxx
uname -a # verify kernel date
more /proc/mtd # verify mtd3 is listed
2. or command line
.. code-block:: bash
# step 1: get the kernel image (uImage.lzma) from slsdetectorgroup
# and copy it to pc's tftp folder
# step 2: connect to the board
telnet bchipxxx
#step 3: go to directory for space
cd /var/tmp/
# step 3: copy kernel to board
tftp pcxxx -r uImage.lzma -g
# step 4: verify kernel copied properly
ls -lrt
# step 5: erase flash
flash_eraseall /dev/mtd1
# step 6: copy new image to kernel drive
cat uImage.lzma > /dev/mtd1
# step 7:
sync
# step 8:
reboot
# step 9: verification
telnet bchipxxx
uname -a # verify kernel date
more /proc/mtd # verify mtd3 is listed
Last Resort using USB Blaster
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

View File

@ -247,6 +247,19 @@ Possible causes could be the following:
* For Jungfrau, refer to :ref:`Jungfrau Power Supply Troubleshooting<Jungfrau Troubleshooting Power Supply>`.
Cannot ping module (Nios)
^^^^^^^^^^^^^^^^^^^^^^^^^
If you executed "reboot" command on the board, you cannot ping it anymore unless you power cycle. To reboot the controller, please use the software command ("rebootcontroller"), which talks to the microcontroller.
Gotthard2
---------
Cannot get data without a module attached
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You cannot get data without a module attached as a specific pin is floating. Attach module to get data.
Gotthard
----------

View File

@ -16,8 +16,8 @@ from parse import remove_comments
allow_bitwise_op = ["M3_GainCaps"]
allow_bitwise_op = ["streamingInterface"]
op_key = {"operator|": "__or__",
"operator&" : "__and__"}
op_key = {"operator|": "|",
"operator&" : "&"}
def single_line_enum(line):
sub = line[line.find('{')+1:line.find('}')]
@ -92,8 +92,7 @@ def generate_enum_string(enums):
#Here add the operators
for op in operators:
data.append(f"\n\t.def(\"{op_key[op]}\", py::overload_cast< const slsDetectorDefs::streamingInterface&, const slsDetectorDefs::streamingInterface&>(&{op}))")
data.append(f"\n\t.def(py::self {op_key[op]} slsDetectorDefs::{key}())")
data.append(';\n\n')
return ''.join(data)

View File

@ -224,6 +224,19 @@ class Detector(CppDetectorApi):
"""
return ut.lhex(self.getDetectorServerVersion())
@property
@element
def kernelversion(self):
"""
Kernel version on the detector including time and date
Example
-------
>>> d.kernelversion
'#37 PREEMPT Thu Oct 13 14:51:04 CEST 2016'
"""
return self.getKernelVersion()
@property
def clientversion(self):
"""Client software version in format [YYMMDD]
@ -1656,6 +1669,7 @@ class Detector(CppDetectorApi):
'client': self.clientversion,
'firmware': self.firmwareversion,
'detectorserver': self.detectorserverversion,
'kernel': self.kernelversion,
'receiver': self.rx_version}
@property
@ -2501,6 +2515,7 @@ class Detector(CppDetectorApi):
-----
:getter: always returns in seconds. To get in datetime.delta, use getBurstPeriod
:setter: Not Implemented
Example
-----------
@ -3422,10 +3437,10 @@ class Detector(CppDetectorApi):
[Gotthard2][Mythen3] Frequency of clock in Hz.
Note
-----
----
:setter: Not implemented. Use clkdiv to set frequency
Example
-------
>>> d.clkfreq[0]

View File

@ -67,6 +67,10 @@ void init_det(py::module &m) {
(Result<int64_t>(Detector::*)(sls::Positions) const) &
Detector::getDetectorServerVersion,
py::arg() = Positions{})
.def("getKernelVersion",
(Result<std::string>(Detector::*)(sls::Positions) const) &
Detector::getKernelVersion,
py::arg() = Positions{})
.def("getSerialNumber",
(Result<int64_t>(Detector::*)(sls::Positions) const) &
Detector::getSerialNumber,
@ -1517,6 +1521,14 @@ void init_det(py::module &m) {
sls::Positions)) &
Detector::copyDetectorServer,
py::arg(), py::arg(), py::arg() = Positions{})
.def("updateDetectorServer",
(void (Detector::*)(const std::string &, sls::Positions)) &
Detector::updateDetectorServer,
py::arg(), py::arg() = Positions{})
.def("updateKernel",
(void (Detector::*)(const std::string &, sls::Positions)) &
Detector::updateKernel,
py::arg(), py::arg() = Positions{})
.def("rebootController",
(void (Detector::*)(sls::Positions)) & Detector::rebootController,
py::arg() = Positions{})
@ -1525,6 +1537,19 @@ void init_det(py::module &m) {
const std::string &, sls::Positions)) &
Detector::updateFirmwareAndServer,
py::arg(), py::arg(), py::arg(), py::arg() = Positions{})
.def("updateFirmwareAndServer",
(void (Detector::*)(const std::string &, const std::string &,
sls::Positions)) &
Detector::updateFirmwareAndServer,
py::arg(), py::arg(), py::arg() = Positions{})
.def("getUpdateMode",
(Result<bool>(Detector::*)(sls::Positions) const) &
Detector::getUpdateMode,
py::arg() = Positions{})
.def("setUpdateMode",
(void (Detector::*)(bool, sls::Positions)) &
Detector::setUpdateMode,
py::arg(), py::arg() = Positions{})
.def("readRegister",
(Result<uint32_t>(Detector::*)(uint32_t, sls::Positions) const) &
Detector::readRegister,

View File

@ -1,4 +1,5 @@
/* WARINING This file is auto generated any edits might be overwritten without warning */
/* WARINING This file is auto generated any edits might be overwritten without
* warning */
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
@ -42,15 +43,19 @@ void init_enums(py::module &m) {
py::enum_<slsDetectorDefs::frameDiscardPolicy>(Defs, "frameDiscardPolicy")
.value("NO_DISCARD", slsDetectorDefs::frameDiscardPolicy::NO_DISCARD)
.value("DISCARD_EMPTY_FRAMES", slsDetectorDefs::frameDiscardPolicy::DISCARD_EMPTY_FRAMES)
.value("DISCARD_PARTIAL_FRAMES", slsDetectorDefs::frameDiscardPolicy::DISCARD_PARTIAL_FRAMES)
.value("NUM_DISCARD_POLICIES", slsDetectorDefs::frameDiscardPolicy::NUM_DISCARD_POLICIES)
.value("DISCARD_EMPTY_FRAMES",
slsDetectorDefs::frameDiscardPolicy::DISCARD_EMPTY_FRAMES)
.value("DISCARD_PARTIAL_FRAMES",
slsDetectorDefs::frameDiscardPolicy::DISCARD_PARTIAL_FRAMES)
.value("NUM_DISCARD_POLICIES",
slsDetectorDefs::frameDiscardPolicy::NUM_DISCARD_POLICIES)
.export_values();
py::enum_<slsDetectorDefs::fileFormat>(Defs, "fileFormat")
.value("BINARY", slsDetectorDefs::fileFormat::BINARY)
.value("HDF5", slsDetectorDefs::fileFormat::HDF5)
.value("NUM_FILE_FORMATS", slsDetectorDefs::fileFormat::NUM_FILE_FORMATS)
.value("NUM_FILE_FORMATS",
slsDetectorDefs::fileFormat::NUM_FILE_FORMATS)
.export_values();
py::enum_<slsDetectorDefs::dimension>(Defs, "dimension")
@ -59,19 +64,25 @@ void init_enums(py::module &m) {
.export_values();
py::enum_<slsDetectorDefs::externalSignalFlag>(Defs, "externalSignalFlag")
.value("TRIGGER_IN_RISING_EDGE", slsDetectorDefs::externalSignalFlag::TRIGGER_IN_RISING_EDGE)
.value("TRIGGER_IN_FALLING_EDGE", slsDetectorDefs::externalSignalFlag::TRIGGER_IN_FALLING_EDGE)
.value("INVERSION_ON", slsDetectorDefs::externalSignalFlag::INVERSION_ON)
.value("INVERSION_OFF", slsDetectorDefs::externalSignalFlag::INVERSION_OFF)
.value("TRIGGER_IN_RISING_EDGE",
slsDetectorDefs::externalSignalFlag::TRIGGER_IN_RISING_EDGE)
.value("TRIGGER_IN_FALLING_EDGE",
slsDetectorDefs::externalSignalFlag::TRIGGER_IN_FALLING_EDGE)
.value("INVERSION_ON",
slsDetectorDefs::externalSignalFlag::INVERSION_ON)
.value("INVERSION_OFF",
slsDetectorDefs::externalSignalFlag::INVERSION_OFF)
.export_values();
py::enum_<slsDetectorDefs::timingMode>(Defs, "timingMode")
.value("AUTO_TIMING", slsDetectorDefs::timingMode::AUTO_TIMING)
.value("TRIGGER_EXPOSURE", slsDetectorDefs::timingMode::TRIGGER_EXPOSURE)
.value("TRIGGER_EXPOSURE",
slsDetectorDefs::timingMode::TRIGGER_EXPOSURE)
.value("GATED", slsDetectorDefs::timingMode::GATED)
.value("BURST_TRIGGER", slsDetectorDefs::timingMode::BURST_TRIGGER)
.value("TRIGGER_GATED", slsDetectorDefs::timingMode::TRIGGER_GATED)
.value("NUM_TIMING_MODES", slsDetectorDefs::timingMode::NUM_TIMING_MODES)
.value("NUM_TIMING_MODES",
slsDetectorDefs::timingMode::NUM_TIMING_MODES)
.export_values();
py::enum_<slsDetectorDefs::dacIndex>(Defs, "dacIndex")
@ -159,13 +170,16 @@ void init_enums(py::module &m) {
.value("HIGH_VOLTAGE", slsDetectorDefs::dacIndex::HIGH_VOLTAGE)
.value("TEMPERATURE_ADC", slsDetectorDefs::dacIndex::TEMPERATURE_ADC)
.value("TEMPERATURE_FPGA", slsDetectorDefs::dacIndex::TEMPERATURE_FPGA)
.value("TEMPERATURE_FPGAEXT", slsDetectorDefs::dacIndex::TEMPERATURE_FPGAEXT)
.value("TEMPERATURE_FPGAEXT",
slsDetectorDefs::dacIndex::TEMPERATURE_FPGAEXT)
.value("TEMPERATURE_10GE", slsDetectorDefs::dacIndex::TEMPERATURE_10GE)
.value("TEMPERATURE_DCDC", slsDetectorDefs::dacIndex::TEMPERATURE_DCDC)
.value("TEMPERATURE_SODL", slsDetectorDefs::dacIndex::TEMPERATURE_SODL)
.value("TEMPERATURE_SODR", slsDetectorDefs::dacIndex::TEMPERATURE_SODR)
.value("TEMPERATURE_FPGA2", slsDetectorDefs::dacIndex::TEMPERATURE_FPGA2)
.value("TEMPERATURE_FPGA3", slsDetectorDefs::dacIndex::TEMPERATURE_FPGA3)
.value("TEMPERATURE_FPGA2",
slsDetectorDefs::dacIndex::TEMPERATURE_FPGA2)
.value("TEMPERATURE_FPGA3",
slsDetectorDefs::dacIndex::TEMPERATURE_FPGA3)
.value("TRIMBIT_SCAN", slsDetectorDefs::dacIndex::TRIMBIT_SCAN)
.value("V_POWER_A", slsDetectorDefs::dacIndex::V_POWER_A)
.value("V_POWER_B", slsDetectorDefs::dacIndex::V_POWER_B)
@ -204,15 +218,20 @@ void init_enums(py::module &m) {
.value("VERYLOWGAIN", slsDetectorDefs::detectorSettings::VERYLOWGAIN)
.value("G1_HIGHGAIN", slsDetectorDefs::detectorSettings::G1_HIGHGAIN)
.value("G1_LOWGAIN", slsDetectorDefs::detectorSettings::G1_LOWGAIN)
.value("G2_HIGHCAP_HIGHGAIN", slsDetectorDefs::detectorSettings::G2_HIGHCAP_HIGHGAIN)
.value("G2_HIGHCAP_LOWGAIN", slsDetectorDefs::detectorSettings::G2_HIGHCAP_LOWGAIN)
.value("G2_LOWCAP_HIGHGAIN", slsDetectorDefs::detectorSettings::G2_LOWCAP_HIGHGAIN)
.value("G2_LOWCAP_LOWGAIN", slsDetectorDefs::detectorSettings::G2_LOWCAP_LOWGAIN)
.value("G2_HIGHCAP_HIGHGAIN",
slsDetectorDefs::detectorSettings::G2_HIGHCAP_HIGHGAIN)
.value("G2_HIGHCAP_LOWGAIN",
slsDetectorDefs::detectorSettings::G2_HIGHCAP_LOWGAIN)
.value("G2_LOWCAP_HIGHGAIN",
slsDetectorDefs::detectorSettings::G2_LOWCAP_HIGHGAIN)
.value("G2_LOWCAP_LOWGAIN",
slsDetectorDefs::detectorSettings::G2_LOWCAP_LOWGAIN)
.value("G4_HIGHGAIN", slsDetectorDefs::detectorSettings::G4_HIGHGAIN)
.value("G4_LOWGAIN", slsDetectorDefs::detectorSettings::G4_LOWGAIN)
.value("GAIN0", slsDetectorDefs::detectorSettings::GAIN0)
.value("UNDEFINED", slsDetectorDefs::detectorSettings::UNDEFINED)
.value("UNINITIALIZED", slsDetectorDefs::detectorSettings::UNINITIALIZED)
.value("UNINITIALIZED",
slsDetectorDefs::detectorSettings::UNINITIALIZED)
.export_values();
py::enum_<slsDetectorDefs::clockIndex>(Defs, "clockIndex")
@ -225,7 +244,8 @@ void init_enums(py::module &m) {
py::enum_<slsDetectorDefs::readoutMode>(Defs, "readoutMode")
.value("ANALOG_ONLY", slsDetectorDefs::readoutMode::ANALOG_ONLY)
.value("DIGITAL_ONLY", slsDetectorDefs::readoutMode::DIGITAL_ONLY)
.value("ANALOG_AND_DIGITAL", slsDetectorDefs::readoutMode::ANALOG_AND_DIGITAL)
.value("ANALOG_AND_DIGITAL",
slsDetectorDefs::readoutMode::ANALOG_AND_DIGITAL)
.export_values();
py::enum_<slsDetectorDefs::speedLevel>(Defs, "speedLevel")
@ -239,14 +259,18 @@ void init_enums(py::module &m) {
py::enum_<slsDetectorDefs::burstMode>(Defs, "burstMode")
.value("BURST_INTERNAL", slsDetectorDefs::burstMode::BURST_INTERNAL)
.value("BURST_EXTERNAL", slsDetectorDefs::burstMode::BURST_EXTERNAL)
.value("CONTINUOUS_INTERNAL", slsDetectorDefs::burstMode::CONTINUOUS_INTERNAL)
.value("CONTINUOUS_EXTERNAL", slsDetectorDefs::burstMode::CONTINUOUS_EXTERNAL)
.value("CONTINUOUS_INTERNAL",
slsDetectorDefs::burstMode::CONTINUOUS_INTERNAL)
.value("CONTINUOUS_EXTERNAL",
slsDetectorDefs::burstMode::CONTINUOUS_EXTERNAL)
.value("NUM_BURST_MODES", slsDetectorDefs::burstMode::NUM_BURST_MODES)
.export_values();
py::enum_<slsDetectorDefs::timingSourceType>(Defs, "timingSourceType")
.value("TIMING_INTERNAL", slsDetectorDefs::timingSourceType::TIMING_INTERNAL)
.value("TIMING_EXTERNAL", slsDetectorDefs::timingSourceType::TIMING_EXTERNAL)
.value("TIMING_INTERNAL",
slsDetectorDefs::timingSourceType::TIMING_INTERNAL)
.value("TIMING_EXTERNAL",
slsDetectorDefs::timingSourceType::TIMING_EXTERNAL)
.export_values();
py::enum_<slsDetectorDefs::M3_GainCaps>(Defs, "M3_GainCaps")
@ -265,14 +289,17 @@ void init_enums(py::module &m) {
.value("BOTTOM", slsDetectorDefs::portPosition::BOTTOM)
.export_values();
py::enum_<slsDetectorDefs::streamingInterface>(Defs, "streamingInterface", py::arithmetic())
py::enum_<slsDetectorDefs::streamingInterface>(Defs, "streamingInterface",
py::arithmetic())
.value("NONE", slsDetectorDefs::streamingInterface::NONE)
.value("LOW_LATENCY_LINK", slsDetectorDefs::streamingInterface::LOW_LATENCY_LINK)
.value("ETHERNET_10GB", slsDetectorDefs::streamingInterface::ETHERNET_10GB)
.value("LOW_LATENCY_LINK",
slsDetectorDefs::streamingInterface::LOW_LATENCY_LINK)
.value("ETHERNET_10GB",
slsDetectorDefs::streamingInterface::ETHERNET_10GB)
.value("ALL", slsDetectorDefs::streamingInterface::ALL)
.export_values()
.def("__or__", py::overload_cast<const slsDetectorDefs::streamingInterface &, const slsDetectorDefs::streamingInterface &>(&operator|))
.def("__and__", py::overload_cast<const slsDetectorDefs::streamingInterface &, const slsDetectorDefs::streamingInterface &>(&operator&));
.def(py::self | slsDetectorDefs::streamingInterface())
.def(py::self & slsDetectorDefs::streamingInterface());
py::enum_<slsDetectorDefs::vetoAlgorithm>(Defs, "vetoAlgorithm")
.value("ALG_HITS", slsDetectorDefs::vetoAlgorithm::ALG_HITS)

View File

@ -0,0 +1,23 @@
from slsdet.enums import streamingInterface
import pytest
def test_streamingInterface_bitwise():
"""Bitwise operations on streaming interfaces are allowed"""
sif_none = streamingInterface.NONE
sif_low = streamingInterface.LOW_LATENCY_LINK
sif_10g = streamingInterface.ETHERNET_10GB
sif_all = streamingInterface.ALL
assert sif_low | sif_none == sif_low
assert sif_10g | sif_none == sif_10g
assert sif_low | sif_10g == sif_all
assert sif_10g | sif_all == sif_all
assert sif_10g & sif_low == sif_none
assert sif_low & sif_low == sif_low
assert sif_all & sif_all == sif_all
def test_streamingInterface_bitwise_only_allowed_on_same_type():
with pytest.raises(Exception):
assert streamingInterface.LOW_LATENCY_LINK & 5 == 7

View File

@ -1 +0,0 @@
../slsDetectorServers/ctbDetectorServer/bin/ctbDetectorServerv6.0.0

View File

@ -0,0 +1 @@
../slsDetectorServers/ctbDetectorServer/bin/ctbDetectorServerv6.1.0

View File

@ -1 +0,0 @@
../slsDetectorServers/eigerDetectorServer/bin/eigerDetectorServerv6.0.0

View File

@ -0,0 +1 @@
../slsDetectorServers/eigerDetectorServer/bin/eigerDetectorServerv6.1.0

View File

@ -1 +0,0 @@
../slsDetectorServers/gotthard2DetectorServer/bin/gotthard2DetectorServerv6.0.0

View File

@ -0,0 +1 @@
../slsDetectorServers/gotthard2DetectorServer/bin/gotthard2DetectorServerv6.1.0

View File

@ -1 +0,0 @@
../slsDetectorServers/gotthardDetectorServer/bin/gotthardDetectorServerv6.0.0

View File

@ -0,0 +1 @@
../slsDetectorServers/gotthardDetectorServer/bin/gotthardDetectorServerv6.1.0

View File

@ -1 +0,0 @@
../slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServerv6.0.0

View File

@ -0,0 +1 @@
../slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServerv6.1.1

View File

@ -1 +0,0 @@
../slsDetectorServers/moenchDetectorServer/bin/moenchDetectorServerv6.0.0

View File

@ -0,0 +1 @@
../slsDetectorServers/moenchDetectorServer/bin/moenchDetectorServerv6.1.0

View File

@ -1 +0,0 @@
../slsDetectorServers/mythen3DetectorServer/bin/mythen3DetectorServerv6.0.0

View File

@ -0,0 +1 @@
../slsDetectorServers/mythen3DetectorServer/bin/mythen3DetectorServerv6.1.0

Binary file not shown.

Binary file not shown.

View File

@ -39,7 +39,7 @@ foreach(exe ${MOENCH_EXECUTABLES})
set_target_properties(${exe} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
if(SLS_LTO_AVAILABLE)
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET ${exe} PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()

View File

@ -110,7 +110,7 @@ target_link_libraries(slsDetectorGui PUBLIC
set_target_properties(slsDetectorGui PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
if(SLS_LTO_AVAILABLE)
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET slsDetectorGui PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()

View File

@ -17,7 +17,7 @@ add_executable(ctbDetectorServer_virtual
../slsDetectorServer/src/INA226.c
../slsDetectorServer/src/LTC2620.c
../slsDetectorServer/src/MAX1932.c
../slsDetectorServer/src/programFpgaBlackfin.c
../slsDetectorServer/src/programViaBlackfin.c
../slsDetectorServer/src/sharedMemory.c
../slsDetectorServer/src/loadPattern.c
../../slsSupportLib/src/md5.c

View File

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

View File

@ -97,8 +97,14 @@ void basictests() {
return;
#else
defineGPIOpins();
resetFPGA();
initError = defineGPIOpins(initErrorMessage);
if (initError == FAIL) {
return;
}
initError = resetFPGA(initErrorMessage);
if (initError == FAIL) {
return;
}
if (mapCSP0() == FAIL) {
strcpy(initErrorMessage,
"Could not map to memory. Dangerous to continue.\n");

View File

@ -2699,9 +2699,6 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) {
LOG(logDEBUG1, ("DACs: src %d, dest %d\n", srcMod->ndac, destMod->ndac));
LOG(logDEBUG1, ("Chans: src %d, dest %d\n", srcMod->nchan, destMod->nchan));
destMod->ndac = srcMod->ndac;
destMod->nchip = srcMod->nchip;
destMod->nchan = srcMod->nchan;
if (srcMod->reg >= 0)
destMod->reg = srcMod->reg;
if (srcMod->iodelay >= 0)
@ -2712,7 +2709,7 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) {
destMod->eV[0] = srcMod->eV[0];
LOG(logDEBUG1, ("Copying register %x (%x)\n", destMod->reg, srcMod->reg));
if (destMod->nchan != 0) {
if (destMod->nchan != 0 && srcMod->nchan != 0) {
for (int ichan = 0; ichan < (srcMod->nchan); ichan++) {
if (*((srcMod->chanregs) + ichan) >= 0)
*((destMod->chanregs) + ichan) = *((srcMod->chanregs) + ichan);

View File

@ -12,7 +12,7 @@ add_executable(gotthard2DetectorServer_virtual
../slsDetectorServer/src/LTC2620_Driver.c
../slsDetectorServer/src/ALTERA_PLL_CYCLONE10.c
../slsDetectorServer/src/ASIC_Driver.c
../slsDetectorServer/src/programFpgaNios.c
../slsDetectorServer/src/programViaNios.c
../slsDetectorServer/src/sharedMemory.c
../../slsSupportLib/src/md5.c
)

View File

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

View File

@ -101,7 +101,7 @@ void basictests() {
}
// does check only if flag is 0 (by default), set by command line
if ((!debugflag) && (!updateFlag) &&
((checkKernelVersion() == FAIL) || (checkType() == FAIL) ||
((validateKernelVersion(KERNEL_DATE_VRSN) == FAIL) || (checkType() == FAIL) ||
(testFpga() == FAIL) || (testBus() == FAIL))) {
sprintf(initErrorMessage,
"Could not pass basic tests of FPGA and bus. Dangerous to "
@ -184,13 +184,6 @@ void basictests() {
#endif
}
int checkKernelVersion() {
#ifdef VIRTUAL
return OK;
#endif
return Nios_checkKernelVersion(KERNEL_DATE_VRSN);
}
int checkType() {
#ifdef VIRTUAL
return OK;
@ -2090,24 +2083,40 @@ int setReadoutSpeed(int val) {
case G2_108MHZ:
LOG(logINFOBLUE, ("Setting readout speed to 108 MHz\n"));
if (setClockDivider(READOUT_C0, SPEED_108_CLKDIV_0) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set readout clk 0 to %d\n", SPEED_108_CLKDIV_0));
return FAIL;
}
if (setClockDivider(READOUT_C1, SPEED_108_CLKDIV_1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set readout clk 1 to %d\n", SPEED_108_CLKDIV_1));
return FAIL;
}
if (setPhase(READOUT_C1, SPEED_108_CLKPHASE_DEG_1, 1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set clk phase 1 %d deg\n", SPEED_108_CLKPHASE_DEG_1));
return FAIL;
}
setDBITPipeline(SPEED_144_DBIT_PIPELINE);
if (getDBITPipeline() != SPEED_144_DBIT_PIPELINE) {
LOG(logERROR, ("Could not set readout speed to 108 MHz. Failed to set dbitpipeline to %d \n", SPEED_144_DBIT_PIPELINE));
return FAIL;
}
break;
case G2_144MHZ:
LOG(logINFOBLUE, ("Setting readout speed to 144 MHz\n"));
if (setClockDivider(READOUT_C0, SPEED_144_CLKDIV_0) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set readout clk 0 to %d\n", SPEED_144_CLKDIV_0));
return FAIL;
}
if (setClockDivider(READOUT_C1, SPEED_144_CLKDIV_1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set readout clk 1 to %d\n", SPEED_144_CLKDIV_1));
return FAIL;
}
if (setPhase(READOUT_C1, SPEED_144_CLKPHASE_DEG_1, 1) == FAIL) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set clk phase 1 %d deg\n", SPEED_144_CLKPHASE_DEG_1));
return FAIL;
}
setDBITPipeline(SPEED_144_DBIT_PIPELINE);
if (getDBITPipeline() != SPEED_144_DBIT_PIPELINE) {
LOG(logERROR, ("Could not set readout speed to 144 MHz. Failed to set dbitpipeline to %d \n", SPEED_144_DBIT_PIPELINE));
return FAIL;
}
break;

View File

@ -4,7 +4,7 @@
#include "sls/sls_detector_defs.h"
#define REQRD_FRMWRE_VRSN (0x210527)
#define KERNEL_DATE_VRSN "Wed May 20 13:58:38 CEST 2020"
#define KERNEL_DATE_VRSN "Mon May 10 18:00:21 CEST 2021"
#define ID_FILE "detid_gotthard2.txt"
#define LINKED_SERVER_NAME "gotthard2DetectorServer"
@ -67,9 +67,11 @@
#define SPEED_144_CLKDIV_0 (6)
#define SPEED_144_CLKDIV_1 (6)
#define SPEED_144_CLKPHASE_DEG_1 (122) // 125 not possible
#define SPEED_144_DBIT_PIPELINE (1)
#define SPEED_108_CLKDIV_0 (8)
#define SPEED_108_CLKDIV_1 (8)
#define SPEED_108_CLKPHASE_DEG_1 (268) // 270 not possible
#define SPEED_108_DBIT_PIPELINE (1)
/* Firmware Definitions */
#define FIXED_PLL_FREQUENCY (20000000) // 20MHz

View File

@ -11,6 +11,7 @@ add_executable(gotthardDetectorServer_virtual
../slsDetectorServer/src/LTC2620.c
../slsDetectorServer/src/common.c
../slsDetectorServer/src/commonServerFunctions.c
../slsDetectorServer/src/programViaBlackfin.c
../slsDetectorServer/src/communication_funcs_UDP.c
../slsDetectorServer/src/sharedMemory.c
../../slsSupportLib/src/md5.c

View File

@ -15,7 +15,7 @@ DESTDIR ?= bin
INSTMODE = 0777
SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)AD9252.c $(main_src)AD9257.c $(main_src)LTC2620.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)/sharedMemory.c $(md5_dir)md5.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)AD9252.c $(main_src)AD9257.c $(main_src)LTC2620.c $(main_src)programViaBlackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)/sharedMemory.c $(md5_dir)md5.c
OBJS = $(SRCS:.c=.o)
all: clean $(PROGS)

View File

@ -6,6 +6,8 @@
#define LINKED_SERVER_NAME "gotthardDetectorServer"
#define CTRL_SRVR_INIT_TIME_US (300 * 1000)
/* Enums */
enum ADCINDEX { TEMP_FPGA, TEMP_ADC };
enum DACINDEX {

View File

@ -12,7 +12,7 @@ add_executable(jungfrauDetectorServer_virtual
../slsDetectorServer/src/ALTERA_PLL.c
../slsDetectorServer/src/LTC2620.c
../slsDetectorServer/src/MAX1932.c
../slsDetectorServer/src/programFpgaBlackfin.c
../slsDetectorServer/src/programViaBlackfin.c
../slsDetectorServer/src/communication_funcs_UDP.c
../slsDetectorServer/src/sharedMemory.c
../../slsSupportLib/src/md5.c

View File

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

View File

@ -74,8 +74,14 @@ void basictests() {
}
return;
#else
defineGPIOpins();
resetFPGA();
initError = defineGPIOpins(initErrorMessage);
if (initError == FAIL) {
return;
}
initError = resetFPGA(initErrorMessage);
if (initError == FAIL) {
return;
}
if (mapCSP0() == FAIL) {
strcpy(initErrorMessage,
"Could not map to memory. Dangerous to continue.\n");
@ -495,12 +501,14 @@ void setupDetector() {
// temp threshold and reset event
setThresholdTemperature(DEFAULT_TMP_THRSHLD);
setTemperatureEvent(0);
setFlipRows(DEFAULT_FLIP_ROWS);
if (getChipVersion() == 11) {
setFilterResistor(DEFAULT_FILTER_RESISTOR);
setNumberOfFilterCells(DEFAULT_FILTER_CELL);
}
setReadNRows(MAX_ROWS_PER_READOUT);
if (!isHardwareVersion2()) {
setFlipRows(DEFAULT_FLIP_ROWS);
setReadNRows(MAX_ROWS_PER_READOUT);
}
}
int resetToDefaultDacs(int hardReset) {
@ -1665,6 +1673,11 @@ int setReadNRows(int value) {
LOG(logERROR, ("Invalid number of rows %d\n", value));
return FAIL;
}
if (isHardwareVersion2()) {
LOG(logERROR, ("Could not set number of rows. Only available for "
"Hardware Board version 2.0.\n"));
return FAIL;
}
// regval is numpackets - 1
int regval = (value / READ_N_ROWS_MULTIPLE) - 1;
@ -1673,7 +1686,6 @@ int setReadNRows(int value) {
bus_w(addr, bus_r(addr) & ~READ_N_ROWS_NUM_ROWS_MSK);
bus_w(addr, bus_r(addr) | ((regval << READ_N_ROWS_NUM_ROWS_OFST) &
READ_N_ROWS_NUM_ROWS_MSK));
if (value == MAX_ROWS_PER_READOUT) {
LOG(logINFO, ("Disabling Partial Readout (#rows)\n"));
bus_w(addr, bus_r(addr) & ~READ_N_ROWS_ENBL_MSK);
@ -1685,6 +1697,10 @@ int setReadNRows(int value) {
}
int getReadNRows() {
// cannot set it in old board
if (isHardwareVersion2()) {
return MAX_ROWS_PER_READOUT;
}
int enable = (bus_r(READ_N_ROWS_REG) & READ_N_ROWS_ENBL_MSK);
int regval = ((bus_r(READ_N_ROWS_REG) & READ_N_ROWS_NUM_ROWS_MSK) >>
READ_N_ROWS_NUM_ROWS_OFST);
@ -2157,6 +2173,11 @@ int getFlipRows() {
}
void setFlipRows(int arg) {
if (isHardwareVersion2()) {
LOG(logERROR, ("Could not set flip rows. Only available for "
"Hardware Board version 2.0.\n"));
return;
}
if (arg >= 0) {
if (arg == 0) {
LOG(logINFO, ("Switching off bottom row flipping\n"));
@ -2625,6 +2646,7 @@ int stopStateMachine() {
LOG(logINFO, ("Status Register: %08x\n", bus_r(STATUS_REG)));
usleep(100 * 1000);
resetCore();
return OK;
}

View File

@ -14,7 +14,7 @@ add_executable(moenchDetectorServer_virtual
../slsDetectorServer/src/ALTERA_PLL.c
../slsDetectorServer/src/LTC2620.c
../slsDetectorServer/src/MAX1932.c
../slsDetectorServer/src/programFpgaBlackfin.c
../slsDetectorServer/src/programViaBlackfin.c
../slsDetectorServer/src/loadPattern.c
../slsDetectorServer/src/sharedMemory.c
../../slsSupportLib/src/md5.c

View File

@ -16,7 +16,7 @@ DESTDIR ?= bin
INSTMODE = 0777
SRCS = slsDetectorFunctionList.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)communication_funcs_UDP.c $(main_src)UDPPacketHeaderGenerator.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programFpgaBlackfin.c $(main_src)loadPattern.c $(main_src)/sharedMemory.c $(md5_dir)md5.c
SRCS += $(main_src)slsDetectorServer.c $(main_src)slsDetectorServer_funcs.c $(main_src)communication_funcs.c $(main_src)blackfin.c $(main_src)common.c $(main_src)commonServerFunctions.c $(main_src)communication_funcs_UDP.c $(main_src)UDPPacketHeaderGenerator.c $(main_src)AD9257.c $(main_src)ALTERA_PLL.c $(main_src)LTC2620.c $(main_src)MAX1932.c $(main_src)programViaBlackfin.c $(main_src)loadPattern.c $(main_src)/sharedMemory.c $(md5_dir)md5.c
OBJS = $(SRCS:.c=.o)

View File

@ -94,8 +94,14 @@ void basictests() {
return;
#else
defineGPIOpins();
resetFPGA();
initError = defineGPIOpins(initErrorMessage);
if (initError == FAIL) {
return;
}
initError = resetFPGA(initErrorMessage);
if (initError == FAIL) {
return;
}
if (mapCSP0() == FAIL) {
strcpy(initErrorMessage,
"Could not map to memory. Dangerous to continue.\n");

View File

@ -12,7 +12,7 @@ add_executable(mythen3DetectorServer_virtual
../slsDetectorServer/src/common.c
../slsDetectorServer/src/LTC2620_Driver.c
../slsDetectorServer/src/ALTERA_PLL_CYCLONE10.c
../slsDetectorServer/src/programFpgaNios.c
../slsDetectorServer/src/programViaNios.c
../slsDetectorServer/src/loadPattern.c
../slsDetectorServer/src/sharedMemory.c
../../slsSupportLib/src/md5.c

View File

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

View File

@ -96,8 +96,9 @@ void basictests() {
}
// does check only if flag is 0 (by default), set by command line
if ((!debugflag) && (!updateFlag) &&
((checkKernelVersion() == FAIL) || (checkType() == FAIL) ||
(testFpga() == FAIL) || (testBus() == FAIL))) {
((validateKernelVersion(KERNEL_DATE_VRSN) == FAIL) ||
(checkType() == FAIL) || (testFpga() == FAIL) ||
(testBus() == FAIL))) {
strcpy(initErrorMessage, "Could not pass basic tests of FPGA and bus. "
"Dangerous to continue.\n");
LOG(logERROR, ("%s\n\n", initErrorMessage));
@ -177,13 +178,6 @@ void basictests() {
#endif
}
int checkKernelVersion() {
#ifdef VIRTUAL
return OK;
#endif
return Nios_checkKernelVersion(KERNEL_DATE_VRSN);
}
int checkType() {
#ifdef VIRTUAL
return OK;
@ -2494,9 +2488,6 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) {
LOG(logDEBUG1, ("DACs: src %d, dest %d\n", srcMod->ndac, destMod->ndac));
LOG(logDEBUG1, ("Chans: src %d, dest %d\n", srcMod->nchan, destMod->nchan));
destMod->ndac = srcMod->ndac;
destMod->nchip = srcMod->nchip;
destMod->nchan = srcMod->nchan;
if (srcMod->reg >= 0)
destMod->reg = srcMod->reg;
/*
@ -2512,7 +2503,7 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) {
LOG(logDEBUG1, ("Copying register %x (%x)\n", destMod->reg, srcMod->reg));
if (destMod->nchan != 0) {
if (destMod->nchan != 0 && srcMod->nchan != 0) {
for (int ichan = 0; ichan < (srcMod->nchan); ichan++) {
*((destMod->chanregs) + ichan) = *((srcMod->chanregs) + ichan);
}

View File

@ -4,7 +4,7 @@
#include "sls/sls_detector_defs.h"
#define REQRD_FRMWRE_VRSN (0x210910)
#define KERNEL_DATE_VRSN "Wed May 20 13:58:38 CEST 2020"
#define KERNEL_DATE_VRSN "Mon May 10 18:00:21 CEST 2021"
#define ID_FILE "detid_mythen3.txt"
#define LINKED_SERVER_NAME "mythen3DetectorServer"

View File

@ -8,7 +8,18 @@
#include <sys/types.h>
#include <time.h>
#define UPDATE_FILE "update.txt"
#ifdef VIRTUAL
#define TEMP_PROG_FOLDER_NAME "/tmp/"
#else
#define TEMP_PROG_FOLDER_NAME "/var/tmp/"
#define TEMP_PROG_FOLDER_NAME_ALL_FILES "/var/tmp/*"
#endif
#define TEMP_PROG_FILE_NAME TEMP_PROG_FOLDER_NAME "tmp.rawbin"
enum numberMode { DEC, HEX };
enum PROGRAM_INDEX { PROGRAM_FPGA, PROGRAM_KERNEL, PROGRAM_SERVER };
/**
* Convert a value from a range to a different range (eg voltage to dac or vice
@ -26,7 +37,11 @@ int ConvertToDifferentRange(int inputMin, int inputMax, int outputMin,
int getAbsPath(char *buf, size_t bufSize, char *fname);
int GetTimeFromString(char *buf, time_t *result);
int getTimeFromString(char *buf, time_t *result);
int getKernelVersion(char *retvals);
int validateKernelVersion(char *expectedVersion);
void validate(int *ret, char *mess, int arg, int retval, char *modename,
enum numberMode nummode);
@ -34,9 +49,20 @@ void validate64(int *ret, char *mess, int64_t arg, int64_t retval,
char *modename, enum numberMode nummode);
int getModuleIdInFile(int *ret, char *mess, char *fileName);
int verifyChecksumFromBuffer(char *mess, char *clientChecksum, char *buffer,
ssize_t bytes);
int verifyChecksumFromFile(char *mess, char *clientChecksum, char *fname);
int verifyChecksumFromFlash(char *mess, char *clientChecksum, char *fname,
ssize_t fsize);
int verifyChecksum(char *mess, char *clientChecksum, MD5_CTX *c, char *msg);
int verifyChecksumFromBuffer(char *mess, char *functionType,
char *clientChecksum, char *buffer, ssize_t bytes);
int verifyChecksumFromFile(char *mess, char *functionType, char *clientChecksum,
char *fname);
int verifyChecksumFromFlash(char *mess, char *functionType,
char *clientChecksum, char *fname, ssize_t fsize);
int verifyChecksum(char *mess, char *functionType, char *clientChecksum,
MD5_CTX *c, char *msg);
int setupDetectorServer(char *mess, char *sname);
int writeBinaryFile(char *mess, char *fname, char *buffer,
const uint64_t filesize, char *errorPrefix);
int moveBinaryFile(char *mess, char *dest, char *src, char *errorPrefix);
int createEmptyFile(char *mess, char *fname, char *errorPrefix);
int deleteFile(char *mess, char *fname, char *errorPrefix);

View File

@ -89,7 +89,3 @@ int mapCSP0(void);
* Get Nios base address
*/
u_int32_t *Nios_getBaseAddress();
/** check kernel version against expected version string (complain if too old)
* @returns OK or FAIL */
int Nios_checkKernelVersion(char *expectedVersion);

View File

@ -1,32 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#include <stdint.h>
#include <stdio.h>
#include <sys/types.h>
#define TEMP_PROG_FILE_NAME "/var/tmp/tmp.rawbin"
void defineGPIOpins();
void FPGAdontTouchFlash();
void FPGATouchFlash();
void resetFPGA();
int deleteOldFile(char *mess);
/**
* deletes old file
* verify memory available to copy
* open file to copy
*/
int preparetoCopyFPGAProgram(FILE **fd, uint64_t fsize, char *mess);
int copyToFlash(ssize_t fsize, char *clientChecksum, char *mess);
int getDrive(char *mess);
/** Notify fpga not to touch flash, open src and flash drive to write */
int openFileForFlash(FILE **flashfd, FILE **srcfd, char *mess);
int eraseFlash(char *mess);
/* write from tmp file to flash */
int writeToFlash(ssize_t fsize, FILE *flashfd, FILE *srcfd, char *mess);
/** Notify fpga to pick up firmware from flash and wait for status confirmation
*/
int waitForFPGAtoTouchFlash(char *mess);

View File

@ -0,0 +1,38 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#include "common.h"
#include <stdint.h>
#include <stdio.h>
#include <sys/types.h>
#define BLACKFIN_DEFINED
int defineGPIOpins(char *mess);
int FPGAdontTouchFlash(char *mess);
int FPGATouchFlash(char *mess);
int resetFPGA(char *mess);
int emptyTempFolder(char *mess);
int allowUpdate(char *mess, char *functionType);
/**
* deletes old file
* verify memory available to copy
* open file to copy
*/
int preparetoCopyProgram(char *mess, char *functionType, FILE **fd,
uint64_t fsize);
int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index,
char *functionType, char *clientChecksum,
ssize_t fsize);
int getDrive(char *mess, enum PROGRAM_INDEX index);
/** Notify fpga not to touch flash, open src and flash drive to write */
int openFileForFlash(char *mess, FILE **flashfd, FILE **srcfd);
int eraseFlash(char *mess);
/* write from tmp file to flash */
int writeToFlash(char *mess, ssize_t fsize, FILE *flashfd, FILE *srcfd);
/** Notify fpga to pick up firmware from flash and wait for status confirmation
*/
int waitForFPGAtoTouchFlash(char *mess);

View File

@ -2,6 +2,8 @@
// Copyright (C) 2021 Contributors to the SLS Detector Package
#pragma once
#include "common.h"
#include <stdint.h>
#include <stdio.h>
@ -13,9 +15,10 @@ void NotifyServerStartSuccess();
/** reset fpga and controller(only implemented for >= v1.1 boards) */
void rebootControllerAndFPGA();
int eraseAndWriteToFlash(char *mess, char *checksum, char *fpgasrc,
int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index,
char *functionType, char *checksum, char *fpgasrc,
uint64_t fsize);
int getDrive(char *mess);
int openFileForFlash(FILE **flashfd, char *mess);
int getDrive(char *mess, enum PROGRAM_INDEX index);
int openFileForFlash(char *mess, FILE **flashfd);
int eraseFlash(char *mess);
int writeToFlash(ssize_t fsize, FILE *flashfd, char *buffer, char *mess);
int writeToFlash(char *mess, ssize_t fsize, FILE *flashfd, char *buffer);

View File

@ -12,9 +12,10 @@
#endif
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
#include "programFpgaNios.h"
#elif defined(CHIPTESTBOARDD) || defined(JUNGFRAUD) || defined(MOENCHD)
#include "programFpgaBlackfin.h"
#include "programViaNios.h"
#elif defined(CHIPTESTBOARDD) || defined(JUNGFRAUD) || defined(MOENCHD) || \
defined(GOTTHARDD)
#include "programViaBlackfin.h"
#endif
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
@ -60,9 +61,6 @@ typedef struct udpStruct_s {
int isInitCheckDone();
int getInitResult(char **mess);
void basictests();
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
int checkKernelVersion();
#endif
#if defined(GOTTHARDD) || defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || \
defined(MOENCHD) || defined(MYTHEN3D) || defined(GOTTHARD2D)
int checkType();

View File

@ -9,6 +9,7 @@
#define REBOOT (-400)
// initialization functions
int updateModeAllowedFunction(int file_des);
int printSocketReadError();
void init_detector();
int decode_function(int);
@ -276,4 +277,16 @@ int clear_all_udp_dst(int);
int get_udp_first_dest(int);
int set_udp_first_dest(int);
int get_readout_speed(int);
int set_readout_speed(int);
int set_readout_speed(int);
int get_kernel_version(int);
int update_kernel(int);
int update_detector_server(int);
int receive_program(int file_des, enum PROGRAM_INDEX index);
void receive_program_via_blackfin(int file_des, enum PROGRAM_INDEX index,
char *functionType, uint64_t filesize,
char *checksum, char *serverName);
void receive_program_default(int file_des, enum PROGRAM_INDEX index,
char *functionType, uint64_t filesize,
char *checksum, char *serverName);
int get_update_mode(int);
int set_update_mode(int);

View File

@ -3,6 +3,7 @@
#include "blackfin.h"
#include "RegisterDefs.h"
#include "clogger.h"
#include "common.h"
#include "sls/ansi.h"
#include "sls/sls_detector_defs.h"
@ -126,4 +127,4 @@ int mapCSP0(void) {
return OK;
}
uint32_t *Blackfin_getBaseAddress() { return csp0base; }
uint32_t *Blackfin_getBaseAddress() { return csp0base; }

View File

@ -4,10 +4,14 @@
#include "common.h"
#include "clogger.h"
#include "sls/sls_detector_defs.h"
#include "slsDetectorServer_defs.h"
#include <libgen.h> // dirname
#include <string.h>
#include <unistd.h> // readlink
#include <sys/utsname.h> // uname
#include <unistd.h> // readlink
extern int executeCommand(char *command, char *result, enum TLogLevel level);
int ConvertToDifferentRange(int inputMin, int inputMax, int outputMin,
int outputMax, int inputValue, int *outputValue) {
@ -64,15 +68,105 @@ int getAbsPath(char *buf, size_t bufSize, char *fname) {
return OK;
}
int GetTimeFromString(char *buf, time_t *result) {
int getTimeFromString(char *buf, time_t *result) {
char buffer[255] = {0};
strcpy(buffer, buf);
// remove timezone as strptime cannot validate timezone despite
// documentation (for blackfin)
LOG(logDEBUG, ("kernel v %s\n", buffer));
const char *timezone = {"CEST"};
char *res = strstr(buffer, timezone);
if (res != NULL) {
size_t cestPos = res - buffer;
size_t pos = cestPos + strlen(timezone) + 1;
while (pos != strlen(buffer)) {
buffer[cestPos] = buffer[pos];
++cestPos;
++pos;
}
buffer[cestPos] = '\0';
}
LOG(logDEBUG, ("kernel v after removing CEST %s\n", buffer));
// convert to time structure
struct tm t;
if (NULL == strptime(buf, "%a %b %d %H:%M:%S %Z %Y", &t)) {
if (NULL == strptime(buffer, "%a %b %d %H:%M:%S %Y", &t)) {
return FAIL;
}
// print time structure
LOG(logDEBUG,
("%d %d %d %d:%d:%d %d (day date month H:M:S year)\n", t.tm_wday,
t.tm_mday, t.tm_mon, t.tm_year + 1900, t.tm_hour, t.tm_min, t.tm_sec));
*result = mktime(&t);
return OK;
}
int getKernelVersion(char *retvals) {
struct utsname buf;
memset(&buf, 0, sizeof(buf));
if (uname(&buf) == -1) {
strcpy(retvals, "Failed to get utsname structure from uname\n");
LOG(logERROR, (retvals));
return FAIL;
}
strcpy(retvals, buf.version);
LOG(logINFOBLUE, ("Kernel Version: %s\n", retvals));
return OK;
}
int validateKernelVersion(char *expectedVersion) {
// extract kernel date string
char version[255] = {0};
if (getKernelVersion(version) == FAIL) {
LOG(logERROR, ("Could not validate kernel version\n"));
return FAIL;
}
LOG(logDEBUG, ("utsname.version:%s\n", version));
char currentVersion[255] = {0};
#ifdef VIRTUAL
strcpy(currentVersion, expectedVersion);
#else
// remove first word (#version number)
const char *ptr = strchr(version, ' ');
if (ptr == NULL) {
LOG(logERROR, ("Could not parse kernel version\n"));
return FAIL;
}
strcpy(currentVersion, version + (ptr - version + 1));
#endif
// convert kernel date string into time
time_t kernelDate;
if (getTimeFromString(currentVersion, &kernelDate) == FAIL) {
LOG(logERROR,
("Could not parse retrieved kernel date, %s\n", currentVersion));
return FAIL;
}
// convert expected date into time
time_t expDate;
if (getTimeFromString(expectedVersion, &expDate) == FAIL) {
LOG(logERROR,
("Could not parse expected kernel date, %s\n", expectedVersion));
return FAIL;
}
// compare if kernel time is older than expected time
if (kernelDate < expDate) {
LOG(logERROR, ("Kernel Version Incompatible (too old)! Expected: [%s], "
"Got [%s]\n",
expectedVersion, currentVersion));
return FAIL;
}
LOG(logINFOBLUE, ("Kernel Version Compatible: %s [min.: %s]\n",
currentVersion, expectedVersion));
return OK;
}
void validate(int *ret, char *mess, int arg, int retval, char *modename,
enum numberMode nummode) {
if (*ret == OK && arg != GET_FLAG && retval != arg) {
@ -148,30 +242,39 @@ int getModuleIdInFile(int *ret, char *mess, char *fileName) {
return retval;
}
int verifyChecksumFromBuffer(char *mess, char *clientChecksum, char *buffer,
int verifyChecksumFromBuffer(char *mess, char *functionType,
char *clientChecksum, char *buffer,
ssize_t bytes) {
LOG(logINFO, ("\tVerifying Checksum...\n"));
LOG(logINFO, ("\tVerifying Checksum from memory...\n"));
MD5_CTX c;
if (!MD5_Init_SLS(&c)) {
strcpy(mess, "Unable to calculate checksum (MD5_Init_SLS)\n");
sprintf(mess,
"Could not %s. Unable to calculate checksum (MD5_Init_SLS)\n",
functionType);
LOG(logERROR, (mess));
return FAIL;
}
if (!MD5_Update_SLS(&c, buffer, bytes)) {
strcpy(mess, "Unable to calculate checksum (MD5_Update_SLS)\n");
sprintf(mess,
"Could not %s. Unable to calculate checksum (MD5_Update_SLS)\n",
functionType);
LOG(logERROR, (mess));
return FAIL;
}
return verifyChecksum(mess, clientChecksum, &c, "copied program");
return verifyChecksum(mess, functionType, clientChecksum, &c,
"copied program (buffer)");
}
int verifyChecksumFromFile(char *mess, char *clientChecksum, char *fname) {
LOG(logINFO, ("\tVerifying Checksum...\n"));
int verifyChecksumFromFile(char *mess, char *functionType, char *clientChecksum,
char *fname) {
LOG(logINFO, ("\tVerifying Checksum of file...\n"));
FILE *fp = fopen(fname, "r");
if (fp == NULL) {
sprintf(mess, "Unable to open %s in read mode to get checksum\n",
fname);
sprintf(
mess,
"Could not %s. Unable to open %s in read mode to get checksum\n",
functionType, fname);
LOG(logERROR, (mess));
return FAIL;
}
@ -179,7 +282,9 @@ int verifyChecksumFromFile(char *mess, char *clientChecksum, char *fname) {
MD5_CTX c;
if (!MD5_Init_SLS(&c)) {
fclose(fp);
strcpy(mess, "Unable to calculate checksum (MD5_Init_SLS)\n");
sprintf(mess,
"Could not %s. Unable to calculate checksum (MD5_Init_SLS)\n",
functionType);
LOG(logERROR, (mess));
return FAIL;
}
@ -190,7 +295,10 @@ int verifyChecksumFromFile(char *mess, char *clientChecksum, char *fname) {
while (bytes > 0) {
if (!MD5_Update_SLS(&c, buf, bytes)) {
fclose(fp);
strcpy(mess, "Unable to calculate checksum (MD5_Update_SLS)\n");
sprintf(
mess,
"Could not %s. Unable to calculate checksum (MD5_Update_SLS)\n",
functionType);
LOG(logERROR, (mess));
return FAIL;
}
@ -199,17 +307,20 @@ int verifyChecksumFromFile(char *mess, char *clientChecksum, char *fname) {
}
LOG(logINFO, ("\tRead %lu bytes to calculate checksum\n", totalBytesRead));
fclose(fp);
return verifyChecksum(mess, clientChecksum, &c, "copied program");
return verifyChecksum(mess, functionType, clientChecksum, &c,
"copied program (file)");
}
int verifyChecksumFromFlash(char *mess, char *clientChecksum, char *fname,
ssize_t fsize) {
LOG(logINFO, ("\tVerifying FlashChecksum...\n"));
int verifyChecksumFromFlash(char *mess, char *functionType,
char *clientChecksum, char *fname, ssize_t fsize) {
LOG(logINFO, ("\tVerifying Checksum from flash...\n"));
FILE *fp = fopen(fname, "r");
if (fp == NULL) {
sprintf(mess, "Unable to open %s in read mode to get checksum\n",
fname);
sprintf(
mess,
"Could not %s. Unable to open %s in read mode to get checksum\n",
functionType, fname);
LOG(logERROR, (mess));
return FAIL;
}
@ -217,7 +328,9 @@ int verifyChecksumFromFlash(char *mess, char *clientChecksum, char *fname,
MD5_CTX c;
if (!MD5_Init_SLS(&c)) {
fclose(fp);
strcpy(mess, "Unable to calculate checksum (MD5_Init_SLS)\n");
sprintf(mess,
"Could not %s. Unable to calculate checksum (MD5_Init_SLS)\n",
functionType);
LOG(logERROR, (mess));
return FAIL;
}
@ -237,33 +350,39 @@ int verifyChecksumFromFlash(char *mess, char *clientChecksum, char *fname,
if (!MD5_Update_SLS(&c, buf, bytes)) {
fclose(fp);
strcpy(mess, "Unable to calculate checksum (MD5_Update_SLS)\n");
sprintf(
mess,
"Could not %s. Unable to calculate checksum (MD5_Update_SLS)\n",
functionType);
LOG(logERROR, (mess));
return FAIL;
}
// read only until a particular size (drive)
if (fsize != 0 && totalBytesRead >= fsize) {
LOG(logINFO,
("\tReached %lu bytes. Not reading more\n", totalBytesRead));
break;
}
bytes = fread(buf, 1, readUnitSize, fp);
// for less than 128 bytes
ssize_t bytesToRead = readUnitSize;
if ((readUnitSize + totalBytesRead) > fsize) {
bytesToRead = fsize - totalBytesRead;
}
bytes = fread(buf, 1, bytesToRead, fp);
totalBytesRead += bytes;
}
LOG(logINFO, ("\tRead %lu bytes to calculate checksum\n", totalBytesRead));
fclose(fp);
int ret = verifyChecksum(mess, clientChecksum, &c, "flash");
if (ret == OK) {
LOG(logINFO, ("Checksum in Flash verified\n"));
}
return ret;
return verifyChecksum(mess, functionType, clientChecksum, &c, "flash");
}
int verifyChecksum(char *mess, char *clientChecksum, MD5_CTX *c, char *msg) {
int verifyChecksum(char *mess, char *functionType, char *clientChecksum,
MD5_CTX *c, char *msg) {
unsigned char out[MD5_DIGEST_LENGTH];
if (!MD5_Final_SLS(out, c)) {
strcpy(mess, "Unable to calculate checksum (MD5_Final_SLS)\n");
sprintf(mess,
"Could not %s. Unable to calculate checksum (MD5_Final_SLS)\n",
functionType);
LOG(logERROR, (mess));
return FAIL;
}
@ -283,12 +402,265 @@ int verifyChecksum(char *mess, char *clientChecksum, MD5_CTX *c, char *msg) {
// compare checksum
if (strcmp(clientChecksum, checksum)) {
sprintf(mess,
"Checksum of %s does not match. Client "
"checksum:%s, copied checksum:%s\n",
msg, clientChecksum, checksum);
"Could not %s. Checksum of %s does not match. Client "
"checksum:%s, copied checksum:%s. Please try again before "
"rebooting.\n",
functionType, msg, clientChecksum, checksum);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tChecksum verified\n"));
LOG(logINFO, ("\tChecksum of %s verified\n", msg));
return OK;
}
int setupDetectorServer(char *mess, char *sname) {
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
// give permissions
if (snprintf(cmd, MAX_STR_LENGTH, "chmod 777 %s", sname) >=
MAX_STR_LENGTH) {
strcpy(mess, "Could not copy detector server. Command to give "
"permissions to server is too long\n");
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (permissions). %s\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tPermissions modified\n"));
// symbolic link
const int fileNameSize = 128;
char linkname[fileNameSize];
if (getAbsPath(linkname, fileNameSize, LINKED_SERVER_NAME) == FAIL) {
sprintf(
mess,
"Could not copy detector server. Could not get abs path of current "
"process\n");
LOG(logERROR, (mess));
return FAIL;
}
if (snprintf(cmd, MAX_STR_LENGTH, "ln -sf %s %s", sname, linkname) >=
MAX_STR_LENGTH) {
strcpy(mess, "Could not copy detector server. Command to "
"create symbolic link too long\n");
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (symbolic link). %s\n",
retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tSymbolic link created\n"));
// blackfin boards (respawn) (only kept for backwards compatibility)
#ifndef VIRTUAL
#if defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) || \
defined(GOTTHARDD)
// delete every line with DetectorServer in /etc/inittab
strcpy(cmd, "sed -i '/DetectorServer/d' /etc/inittab");
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (del respawning). %s\n",
retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tinittab: DetectoServer line deleted\n"));
// add new link name to /etc/inittab
if (snprintf(cmd, MAX_STR_LENGTH,
"echo 'ttyS0::respawn:/./%s' >> /etc/inittab",
linkname) >= MAX_STR_LENGTH) {
strcpy(mess, "Could not copy detector server. Command "
"to add new server for spawning is too long\n");
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (respawning). %s\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tinittab: updated for respawning\n"));
#endif
#endif
// sync
strcpy(cmd, "sync");
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (sync). %s\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tsync\n"));
return OK;
}
int writeBinaryFile(char *mess, char *fname, char *buffer,
const uint64_t filesize, char *errorPrefix) {
LOG(logINFO, ("\tWriting Detector Server Binary...\n"));
FILE *fp = fopen(fname, "wb");
if (fp == NULL) {
sprintf(mess,
"Could not %s. (opening file to write(%s). "
"Maybe it is being used? Try another name?\n",
errorPrefix, fname);
LOG(logERROR, (mess));
return FAIL;
}
size_t bytesWritten = 0;
size_t unitSize = 128;
int oldProgress = 0;
while (bytesWritten < filesize) {
// print progress
int progress = (int)(((double)(bytesWritten) / filesize) * 100);
if (oldProgress != progress) {
printf("%d%%\r", progress);
fflush(stdout);
oldProgress = progress;
}
// for less than 128 bytes
ssize_t writeSize = unitSize;
if ((unitSize + bytesWritten) > filesize) {
writeSize = filesize - bytesWritten;
}
size_t bytes = fwrite((char *)buffer + bytesWritten, 1, writeSize, fp);
// write
if (bytes != (size_t)writeSize) {
sprintf(mess,
"Could not %s. Expected to write %lu "
"bytes, wrote %lu bytes). No space left? \n",
errorPrefix, (long unsigned int)filesize,
(long unsigned int)bytesWritten);
LOG(logERROR, (mess));
return FAIL;
}
bytesWritten += bytes;
LOG(logDEBUG1,
("bytesWritten:%lu filesize:%lu\n", bytesWritten, filesize));
}
if (fclose(fp) != 0) {
sprintf(mess, "Could not %s. (closing file pointer)\n", errorPrefix);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tWritten binary to %s (%lu bytes)\n", fname,
(long unsigned int)bytesWritten));
return OK;
}
int moveBinaryFile(char *mess, char *dest, char *src, char *errorPrefix) {
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
// one can move into the current process binary (will not interfere in
// kernel mode)
if (snprintf(cmd, MAX_STR_LENGTH, "mv %s %s", src, dest) >=
MAX_STR_LENGTH) {
sprintf(mess, "Could not %s. Command to move binary is too long\n",
errorPrefix);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH, "Could not %s. (moving). %s\n",
errorPrefix, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tMoved file from %s to %s\n", src, dest));
return OK;
}
int createEmptyFile(char *mess, char *fname, char *errorPrefix) {
const int fileNameSize = 128;
char fullname[fileNameSize];
if (getAbsPath(fullname, fileNameSize, fname) == FAIL) {
sprintf(mess,
"Could not %s. Could not get abs path of current "
"process\n",
errorPrefix);
LOG(logERROR, (mess));
return FAIL;
}
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
if (snprintf(cmd, MAX_STR_LENGTH, "touch %s", fullname) >= MAX_STR_LENGTH) {
sprintf(mess, "Could not %s. Command to create is too long\n",
errorPrefix);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not %s. (creating empty file %s): %s\n", errorPrefix,
fullname, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tEmpty file created: %s (%s)\n", fullname, errorPrefix));
return OK;
}
int deleteFile(char *mess, char *fname, char *errorPrefix) {
const int fileNameSize = 128;
char fullname[fileNameSize];
if (getAbsPath(fullname, fileNameSize, fname) == FAIL) {
sprintf(mess,
"Could not %s. Could not get abs path of current "
"process\n",
errorPrefix);
LOG(logERROR, (mess));
return FAIL;
}
if (access(fullname, F_OK) == 0) {
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
if (snprintf(cmd, MAX_STR_LENGTH, "rm %s", fullname) >=
MAX_STR_LENGTH) {
sprintf(mess, "Could not %s. Command to delete is too long\n",
errorPrefix);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not %s. (deleting file %s). %s\n", errorPrefix,
fullname, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tDeleted file: %s (%s)\n", fullname, errorPrefix));
} else {
LOG(logINFO,
("\tFile does not exist anyway: %s (%s)\n", fullname, errorPrefix));
}
return OK;
}

View File

@ -7,10 +7,8 @@
#include "sls/ansi.h"
#include "sls/sls_detector_defs.h"
#include <fcntl.h> // open
#include <string.h>
#include <sys/mman.h> // mmap
#include <sys/utsname.h> // uname
#include <fcntl.h> // open
#include <sys/mman.h> // mmap
/* global variables */
u_int32_t *csp0base = 0;
@ -132,49 +130,3 @@ int mapCSP0(void) {
}
u_int32_t *Nios_getBaseAddress() { return csp0base; }
int Nios_checkKernelVersion(char *expectedVersion) {
// extract kernel date string
struct utsname buf;
if (uname(&buf) == -1) {
LOG(logERROR, ("Could not get kernel version\n"));
return FAIL;
}
// remove first word (#version number)
const char *ptr = strchr(buf.version, ' ');
if (ptr == NULL) {
LOG(logERROR, ("Could not parse kernel version\n"));
return FAIL;
}
char output[256];
memset(output, 0, 256);
strcpy(output, buf.version + (ptr - buf.version + 1));
// convert kernel date string into time
time_t kernelDate;
if (GetTimeFromString(output, &kernelDate) == FAIL) {
LOG(logERROR, ("Could not parse retrieved kernel date, %s\n", output));
return FAIL;
}
// convert expected date into time
time_t expDate;
if (GetTimeFromString(expectedVersion, &expDate) == FAIL) {
LOG(logERROR,
("Could not parse expected kernel date, %s\n", expectedVersion));
return FAIL;
}
// compare if kernel time is older than expected time
if (kernelDate < expDate) {
LOG(logERROR, ("Kernel Version Incompatible (too old)! Expected: [%s], "
"Got [%s]\n",
expectedVersion, output));
return FAIL;
}
LOG(logINFOBLUE, ("Kernel Version Compatible: %s [min.: %s]\n", output,
expectedVersion));
return OK;
}

View File

@ -1,381 +0,0 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "programFpgaBlackfin.h"
#include "clogger.h"
#include "common.h"
#include "sls/ansi.h"
#include "slsDetectorServer_defs.h"
#include <string.h>
#include <sys/sysinfo.h>
#include <unistd.h> // usleep
/* global variables */
// clang-format off
#define MAX_TIME_FPGA_TOUCH_FLASH_US (10 * 1000 * 1000) // 10s
#define CMD_GET_FLASH "awk \'$4== \"\\\"bitfile(spi)\\\"\" {print $1}\' /proc/mtd"
#define CMD_FPGA_PICKED_STATUS "cat /sys/class/gpio/gpio7/value"
#define FLASH_BUFFER_MEMORY_SIZE (128 * 1024) // 500 KB
// clang-format on
#define FLASH_DRIVE_NAME_SIZE 16
char flashDriveName[FLASH_DRIVE_NAME_SIZE] = {0};
int gpioDefined = 0;
extern int executeCommand(char *command, char *result, enum TLogLevel level);
void defineGPIOpins() {
#ifdef VIRTUAL
return;
#endif
if (!gpioDefined) {
// define the gpio pins
system("echo 7 > /sys/class/gpio/export");
system("echo 9 > /sys/class/gpio/export");
// define their direction
system("echo in > /sys/class/gpio/gpio7/direction");
system("echo out > /sys/class/gpio/gpio9/direction");
LOG(logINFO, ("gpio pins defined\n"));
gpioDefined = 1;
} else
LOG(logDEBUG1, ("gpio pins already defined earlier\n"));
}
void FPGAdontTouchFlash() {
#ifdef VIRTUAL
return;
#endif
// tell FPGA to not touch flash
system("echo 0 > /sys/class/gpio/gpio9/value");
// usleep(100*1000);
}
void FPGATouchFlash() {
#ifdef VIRTUAL
return;
#endif
// tell FPGA to touch flash to program itself
system("echo 1 > /sys/class/gpio/gpio9/value");
}
void resetFPGA() {
LOG(logINFOBLUE, ("Reseting FPGA\n"));
#ifdef VIRTUAL
return;
#endif
FPGAdontTouchFlash();
FPGATouchFlash();
usleep(CTRL_SRVR_INIT_TIME_US);
}
int deleteOldFile(char *mess) {
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
char *format = "rm -fr %s";
if (snprintf(cmd, MAX_STR_LENGTH, format, TEMP_PROG_FILE_NAME) >=
MAX_STR_LENGTH) {
strcpy(
mess,
"Could not program fpga. Command to delete old file is too long\n");
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not program fpga. (could not delete old file: %s)\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
}
LOG(logINFO,
("\tDeleted old programming file (%s)\n", TEMP_PROG_FILE_NAME));
return OK;
}
int preparetoCopyFPGAProgram(FILE **fd, uint64_t fsize, char *mess) {
if (deleteOldFile(mess) == FAIL) {
return FAIL;
}
// check available memory to copy program
{
struct sysinfo info;
sysinfo(&info);
if (fsize >= info.freeram) {
sprintf(mess,
"Could not program fpga. Not enough memory to copy "
"program. [File size:%ldMB, free RAM: %ldMB]\n",
(long int)(fsize / (1024 * 1024)),
(long int)(info.freeram / (1024 * 1024)));
LOG(logERROR, (mess));
return FAIL;
}
}
// open file to copy program
*fd = fopen(TEMP_PROG_FILE_NAME, "w");
if (*fd == NULL) {
sprintf(mess, "Unable to open %s in write mode\n", TEMP_PROG_FILE_NAME);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tGoing to copy program to %s\n", TEMP_PROG_FILE_NAME));
return OK;
}
int copyToFlash(ssize_t fsize, char *clientChecksum, char *mess) {
if (getDrive(mess) == FAIL) {
return FAIL;
}
FILE *flashfd = NULL;
FILE *srcfd = NULL;
if (openFileForFlash(&flashfd, &srcfd, mess) == FAIL) {
return FAIL;
}
if (eraseFlash(mess) == FAIL) {
fclose(flashfd);
fclose(srcfd);
return FAIL;
}
if (writeToFlash(fsize, flashfd, srcfd, mess) == FAIL) {
return FAIL;
}
if (deleteOldFile(mess) == FAIL) {
return FAIL;
}
/* ignoring this until a consistent way to read from bfin flash
if (verifyChecksumFromFlash(mess, clientChecksum, flashDriveName, fsize)
== FAIL) { return FAIL;
}
*/
if (waitForFPGAtoTouchFlash(mess) == FAIL) {
return FAIL;
}
return OK;
}
int getDrive(char *mess) {
#ifdef VIRTUAL
strcpy(flashDriveName, "/tmp/SLS_mtd3");
return OK;
#endif
LOG(logDEBUG1, ("Finding flash drive...\n"));
// getting the drive
// root:/> cat /proc/mtd
// dev: size erasesize name
// mtd0: 00040000 00020000 "bootloader(nor)"
// mtd1: 00100000 00020000 "linux kernel(nor)"
// mtd2: 002c0000 00020000 "file system(nor)"
// mtd3: 01000000 00010000 "bitfile(spi)"
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
strcpy(cmd, CMD_GET_FLASH);
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not program fpga. (could not get flash drive: %s)\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
}
char *pch = strtok(retvals, ":");
if (pch == NULL) {
strcpy(mess, "Could not get mtd drive to flash (strtok fail).\n");
LOG(logERROR, (mess));
return FAIL;
}
memset(flashDriveName, 0, sizeof(flashDriveName));
strcpy(flashDriveName, "/dev/");
strcat(flashDriveName, pch);
LOG(logINFO, ("\tFlash drive found: %s\n", flashDriveName));
return OK;
}
int openFileForFlash(FILE **flashfd, FILE **srcfd, char *mess) {
FPGAdontTouchFlash();
// open src file
*srcfd = fopen(TEMP_PROG_FILE_NAME, "r");
if (*srcfd == NULL) {
sprintf(mess,
"Could not flash. Unable to open temp program file %s in read "
"mode\n",
TEMP_PROG_FILE_NAME);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logDEBUG1, ("Temp file ready for reading\n"));
// open flash drive for writing
*flashfd = fopen(flashDriveName, "w");
if (*flashfd == NULL) {
fclose(*srcfd);
sprintf(mess, "Unable to open flash drive %s in write mode\n",
flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tFlash ready for writing\n"));
return OK;
}
int eraseFlash(char *mess) {
LOG(logINFO, ("\tErasing Flash...\n"));
#ifdef VIRTUAL
return OK;
#endif
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
char *format = "flash_eraseall %s";
if (snprintf(cmd, MAX_STR_LENGTH, format, flashDriveName) >=
MAX_STR_LENGTH) {
strcpy(mess,
"Could not program fpga. Command to erase flash is too long\n");
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not program fpga. (could not erase flash: %s)\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
}
LOG(logINFO, ("\tFlash erased\n"));
return OK;
}
int writeToFlash(ssize_t fsize, FILE *flashfd, FILE *srcfd, char *mess) {
LOG(logDEBUG1, ("writing to flash\n"));
char *buffer = malloc(FLASH_BUFFER_MEMORY_SIZE);
if (buffer == NULL) {
fclose(flashfd);
fclose(srcfd);
strcpy(mess, "Could not program fpga. Memory allocation to write to "
"flash failed.\n");
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tWriting to Flash...\n"));
int oldProgress = 0;
ssize_t totalBytes = 0;
ssize_t bytes =
fread((void *)buffer, sizeof(char), FLASH_BUFFER_MEMORY_SIZE, srcfd);
while (bytes > 0) {
ssize_t bytesWritten =
fwrite((void *)buffer, sizeof(char), bytes, flashfd);
totalBytes += bytesWritten;
if (bytesWritten != bytes) {
free(buffer);
fclose(flashfd);
fclose(srcfd);
sprintf(mess,
"Could not write to flash (bytes written:%ld, expected: "
"%ld, total written:%ld)\n",
(long int)bytesWritten, (long int)bytes,
(long int)totalBytes);
LOG(logERROR, (mess));
return FAIL;
}
// print progress
if (fsize > 0) {
int progress = (int)(((double)(totalBytes) / fsize) * 100);
if (oldProgress != progress) {
printf("%d%%\r", progress);
fflush(stdout);
oldProgress = progress;
}
} else
printf(".");
bytes = fread((void *)buffer, sizeof(char), FLASH_BUFFER_MEMORY_SIZE,
srcfd);
}
if (fsize <= 0) {
printf("\n");
}
free(buffer);
fclose(flashfd);
fclose(srcfd);
LOG(logINFO, ("\tWrote %ld bytes to flash\n", totalBytes));
if (totalBytes != fsize) {
sprintf(mess,
"Could not program fpga. Incorrect bytes written to flash %lu "
"[expected: %lu]\n",
totalBytes, fsize);
LOG(logERROR, (mess));
return FAIL;
}
return OK;
}
int waitForFPGAtoTouchFlash(char *mess) {
// touch and program
FPGATouchFlash();
#ifdef VIRTUAL
return OK;
#endif
LOG(logINFO, ("\tWaiting for FPGA to program from flash\n"));
int timeSpent = 0;
int result = 0;
while (result == 0) {
// time taken for fpga to pick up from flash
usleep(1000);
timeSpent += 1000;
if (timeSpent >= MAX_TIME_FPGA_TOUCH_FLASH_US) {
sprintf(
mess,
"Could not program fpga. (exceeded max time allowed: %ds)\n",
MAX_TIME_FPGA_TOUCH_FLASH_US / (1000 * 1000));
LOG(logERROR, (mess));
return FAIL;
}
// read gpio status
char retvals[MAX_STR_LENGTH] = {0};
if (FAIL ==
executeCommand(CMD_FPGA_PICKED_STATUS, retvals, logDEBUG1)) {
snprintf(
mess, MAX_STR_LENGTH,
"Could not program fpga. (could not read gpio status: %s)\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
}
// convert to int
if (sscanf(retvals, "%d\n", &result) != 1) {
snprintf(mess, MAX_STR_LENGTH,
"Could not program fpga. (could not scan int for gpio "
"status: [%s])\n",
retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logDEBUG1, ("gpi07 returned %d\n", result));
}
LOG(logINFO, ("\tFPGA has picked up the program from flash\n"));
return OK;
}

View File

@ -0,0 +1,616 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "programViaBlackfin.h"
#include "clogger.h"
#include "common.h"
#include "sls/ansi.h"
#include "slsDetectorServer_defs.h"
#include <string.h>
#include <sys/sysinfo.h>
#include <unistd.h> // usleep
/* global variables */
// clang-format off
#define MAX_TIME_FPGA_TOUCH_FLASH_US (10 * 1000 * 1000) // 10s
#define CMD_GPIO7_DEFINE "echo 7 > /sys/class/gpio/export"
#define CMD_GPIO9_DEFINE "echo 9 > /sys/class/gpio/export"
#define CMD_GPIO3_DEFINE "echo 3 > /sys/class/gpio/export"
#define CMD_GPIO7_EXIST "/sys/class/gpio/gpio7"
#define CMD_GPIO9_EXIST "/sys/class/gpio/gpio9"
#define CMD_GPIO3_EXIST "/sys/class/gpio/gpio3"
#define CMD_GPIO9_DEFINE_OUT "echo out > /sys/class/gpio/gpio9/direction"
#define CMD_GPIO3_DEFINE_OUT "echo out > /sys/class/gpio/gpio3/direction"
#define CMD_GPIO7_DEFINE_IN "echo in > /sys/class/gpio/gpio7/direction"
#define CMD_GPIO9_DEFINE_IN "echo in > /sys/class/gpio/gpio9/direction"
#define CMD_GPIO3_DEFINE_IN "echo in > /sys/class/gpio/gpio3/direction"
#define CMD_GPIO9_DONT_TOUCH_FLASH "echo 0 > /sys/class/gpio/gpio9/value"
#define CMD_GPIO3_DONT_TOUCH_FLASH "echo 0 > /sys/class/gpio/gpio3/value"
#define CMD_FPGA_PICKED_STATUS "cat /sys/class/gpio/gpio7/value"
#define CMD_GET_FPGA_FLASH_DRIVE "awk \'$4== \"\\\"bitfile(spi)\\\"\" {print $1}\' /proc/mtd"
#define CMD_GET_KERNEL_FLASH_DRIVE "awk \'$4== \"\\\"linux\" {print $1}\' /proc/mtd"
#define CMD_GET_AMD_FLASH "dmesg | grep Amd"
#define FLASH_BUFFER_MEMORY_SIZE (128 * 1024) // 500 KB
// clang-format on
#define FLASH_DRIVE_NAME_SIZE 16
#ifdef VIRTUAL
char flashDriveName[FLASH_DRIVE_NAME_SIZE] = "/tmp/SLS_mtd3";
#else
char flashDriveName[FLASH_DRIVE_NAME_SIZE] = {0};
#endif
char messageType[SHORT_STR_LENGTH] = {0};
extern int executeCommand(char *command, char *result, enum TLogLevel level);
int latestKernelVerified = -1;
#define KERNEL_DATE_VRSN_3GPIO "Fri Oct 29 00:00:00 2021"
int defineGPIOpins(char *mess) {
#ifdef VIRTUAL
return OK;
#endif
// only latest kernel can use gpio3 pins
if (latestKernelVerified == -1) {
if (FAIL == validateKernelVersion(KERNEL_DATE_VRSN_3GPIO)) {
latestKernelVerified = 0;
LOG(logWARNING,
("Kernel too old to use gpio 3 pins. Update kernel to "
"guarantee error-free fpga programming. \n\tNot the end "
"of the world. Continuing with current kernel...\n"));
} else {
latestKernelVerified = 1;
}
}
char retvals[MAX_STR_LENGTH] = {0};
// define gpio7
if (access(CMD_GPIO7_EXIST, F_OK) != 0) {
if (executeCommand(CMD_GPIO7_DEFINE, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not define gpio7 pins for fpga (%s)\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio7: defined\n"));
} else {
LOG(logINFO, ("\tgpio7: already defined\n"));
}
// define gpio7 direction
if (executeCommand(CMD_GPIO7_DEFINE_IN, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not set gpio7 as input for fpga (%s)\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio7: setting intput\n"));
// define gpio9
if (access(CMD_GPIO9_EXIST, F_OK) != 0) {
if (executeCommand(CMD_GPIO9_DEFINE, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not define gpio9 pins for fpga (%s)\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio9: defined\n"));
} else {
LOG(logINFO, ("\tgpio9: already defined\n"));
}
// define gpio3 (not chip enable)
if (latestKernelVerified == 1) {
if (access(CMD_GPIO3_EXIST, F_OK) != 0) {
if (executeCommand(CMD_GPIO3_DEFINE, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not define gpio3 pins for fpga (%s)\n",
retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio3: defined\n"));
} else {
LOG(logINFO, ("\tgpio3: already defined\n"));
}
}
return OK;
}
int FPGAdontTouchFlash(char *mess) {
#ifdef VIRTUAL
return OK;
#endif
char retvals[MAX_STR_LENGTH] = {0};
// define gpio9 as output
if (executeCommand(CMD_GPIO9_DEFINE_OUT, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not set gpio9 as output for fpga (%s)\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio9: setting output\n"));
// define gpio3 as output
if (latestKernelVerified == 1) {
if (executeCommand(CMD_GPIO3_DEFINE_OUT, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not set gpio3 as output for fpga (%s)\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio3: setting output\n"));
}
// tell FPGA to not: gpio9
if (executeCommand(CMD_GPIO9_DONT_TOUCH_FLASH, retvals, logDEBUG1) ==
FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not set gpio9 to not touch flash for fpga (%s)\n",
retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio9: fpga dont touch flash\n"));
// tell FPGA to not: gpio3
if (latestKernelVerified == 1) {
if (executeCommand(CMD_GPIO3_DONT_TOUCH_FLASH, retvals, logDEBUG1) ==
FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not set gpio3 to not touch flash for fpga (%s)\n",
retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio3: fpga dont touch flash\n"));
}
// usleep(100*1000);
return OK;
}
int FPGATouchFlash(char *mess) {
#ifdef VIRTUAL
return OK;
#endif
char retvals[MAX_STR_LENGTH] = {0};
// tell FPGA to touch flash to program itself
if (executeCommand(CMD_GPIO9_DEFINE_IN, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not set gpio9 as input for fpga (%s)\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio9: setting input\n"));
if (latestKernelVerified == 1) {
if (executeCommand(CMD_GPIO3_DEFINE_IN, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not set gpio3 as input for fpga (%s)\n", retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tgpio3: setting input\n"));
}
return OK;
}
int resetFPGA(char *mess) {
LOG(logINFOBLUE, ("Reseting FPGA\n"));
#ifdef VIRTUAL
return OK;
#endif
if (FPGAdontTouchFlash(mess) == FAIL) {
return FAIL;
}
if (FPGATouchFlash(mess) == FAIL) {
return FAIL;
}
usleep(CTRL_SRVR_INIT_TIME_US);
return OK;
}
int emptyTempFolder(char *mess) {
#ifdef VIRTUAL
return OK;
#else
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
if (snprintf(cmd, MAX_STR_LENGTH, "rm -fr %s",
TEMP_PROG_FOLDER_NAME_ALL_FILES) >= MAX_STR_LENGTH) {
sprintf(mess,
"Could not update %s. Command to empty %s folder is too long\n",
messageType, TEMP_PROG_FOLDER_NAME);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not update %s. (could not empty %s folder: %s)\n",
messageType, TEMP_PROG_FOLDER_NAME, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tEmptied temp folder(%s)\n", TEMP_PROG_FOLDER_NAME));
return OK;
#endif
}
int allowUpdate(char *mess, char *functionType) {
LOG(logINFO, ("\tVerifying %s allowed...\n", functionType));
#ifdef VIRTUAL
return OK;
#endif
char retvals[MAX_STR_LENGTH] = {0};
if (executeCommand(CMD_GET_AMD_FLASH, retvals, logDEBUG1) == FAIL) {
// no amd found
if (strstr(retvals, "No result") != NULL) {
LOG(logINFO, ("\tNot Amd Flash\n"));
return OK;
}
// could not figure out if amd
snprintf(
mess, MAX_STR_LENGTH,
"Could not update %s. (Could not figure out if Amd flash: %s)\n",
functionType, retvals);
LOG(logERROR, (mess));
return FAIL;
}
// amd, only current kernel works with amd flash
if (validateKernelVersion(KERNEL_DATE_VRSN_3GPIO) == FAIL) {
getKernelVersion(retvals);
snprintf(mess, MAX_STR_LENGTH,
"Could not update %s. Kernel version %s is too old to "
"update the Amd flash/ root directory. Most likely, blackfin needs rescue or replacement. Please contact us.\n",
functionType, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tAmd flash with compatible kernel version\n"));
return OK;
}
int preparetoCopyProgram(char *mess, char *functionType, FILE **fd,
uint64_t fsize) {
if (emptyTempFolder(mess) == FAIL) {
return FAIL;
}
// check available memory to copy program
{
struct sysinfo info;
sysinfo(&info);
if (fsize >= info.freeram) {
sprintf(mess,
"Could not %s. Not enough memory to copy "
"program. [File size:%ldMB, free RAM: %ldMB]\n",
functionType, (long int)(fsize / (1024 * 1024)),
(long int)(info.freeram / (1024 * 1024)));
LOG(logERROR, (mess));
return FAIL;
}
}
// open file to copy program
*fd = fopen(TEMP_PROG_FILE_NAME, "w");
if (*fd == NULL) {
sprintf(mess, "Could not %s. Unable to open %s in write mode\n",
functionType, TEMP_PROG_FILE_NAME);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tGoing to copy program to %s\n", TEMP_PROG_FILE_NAME));
return OK;
}
int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index,
char *functionType, char *clientChecksum,
ssize_t fsize) {
memset(messageType, 0, sizeof(messageType));
strcpy(messageType, functionType);
if (getDrive(mess, index) == FAIL) {
return FAIL;
}
FILE *flashfd = NULL;
FILE *srcfd = NULL;
if (openFileForFlash(mess, &flashfd, &srcfd) == FAIL) {
return FAIL;
}
if (index == PROGRAM_FPGA) {
if (FPGAdontTouchFlash(mess) == FAIL) {
return FAIL;
}
}
if (eraseFlash(mess) == FAIL) {
fclose(flashfd);
fclose(srcfd);
return FAIL;
}
if (writeToFlash(mess, fsize, flashfd, srcfd) == FAIL) {
return FAIL;
}
if (emptyTempFolder(mess) == FAIL) {
return FAIL;
}
/* remove condition when flash fpga fixed */
if (index == PROGRAM_KERNEL) {
if (verifyChecksumFromFlash(mess, messageType, clientChecksum,
flashDriveName, fsize) == FAIL) {
return FAIL;
}
}
if (index == PROGRAM_FPGA) {
if (waitForFPGAtoTouchFlash(mess) == FAIL) {
return FAIL;
}
}
// kernel
else {
char retvals[MAX_STR_LENGTH] = {0};
if (executeCommand("sync", retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not update %s. (could not sync)\n", messageType);
LOG(logERROR, (mess));
return FAIL;
}
}
return OK;
}
int getDrive(char *mess, enum PROGRAM_INDEX index) {
#ifdef VIRTUAL
return OK;
#endif
LOG(logDEBUG1, ("Finding flash drive...\n"));
// getting the drive
// root:/> cat /proc/mtd
// dev: size erasesize name
// mtd0: 00040000 00020000 "bootloader(nor)"
// mtd1: 00100000 00020000 "linux kernel(nor)"
// mtd2: 002c0000 00020000 "file system(nor)"
// mtd3: 01000000 00010000 "bitfile(spi)"
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
if (index == PROGRAM_FPGA) {
strcpy(cmd, CMD_GET_FPGA_FLASH_DRIVE);
} else {
strcpy(cmd, CMD_GET_KERNEL_FLASH_DRIVE);
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not %s. (could not get flash drive: %s)\n", messageType,
retvals);
LOG(logERROR, (mess));
return FAIL;
}
if (strlen(retvals) == 0) {
LOG(logERROR, ("Could not %s. Could not get mtd drive, script returned "
"empty string\n",
messageType));
return FAIL;
}
char *pch = strtok(retvals, ":");
if (pch == NULL) {
sprintf(mess,
"Could not %s. Could not get mtd drive to flash (strtok "
"fail).\n",
messageType);
LOG(logERROR, (mess));
return FAIL;
}
memset(flashDriveName, 0, sizeof(flashDriveName));
sprintf(flashDriveName, "/dev/%s", pch);
LOG(logINFO, ("\tFlash drive found: %s\n", flashDriveName));
return OK;
}
int openFileForFlash(char *mess, FILE **flashfd, FILE **srcfd) {
// open src file
*srcfd = fopen(TEMP_PROG_FILE_NAME, "r");
if (*srcfd == NULL) {
sprintf(mess,
"Could not %s. Unable to open temp program file %s in read "
"mode\n",
messageType, TEMP_PROG_FILE_NAME);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logDEBUG1, ("Temp file ready for reading\n"));
// open flash drive for writing
*flashfd = fopen(flashDriveName, "w");
if (*flashfd == NULL) {
fclose(*srcfd);
sprintf(mess,
"Could not %s. Unable to open flash drive %s in write "
"mode\n",
messageType, flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tFlash ready for writing\n"));
return OK;
}
int eraseFlash(char *mess) {
LOG(logINFO, ("\tErasing Flash...\n"));
#ifdef VIRTUAL
return OK;
#endif
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
if (snprintf(cmd, MAX_STR_LENGTH, "flash_eraseall %s", flashDriveName) >=
MAX_STR_LENGTH) {
sprintf(mess, "Could not %s. Command to erase flash is too long\n",
messageType);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not update %s. (could not erase flash: %s)\n",
messageType, retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tFlash erased\n"));
return OK;
}
int writeToFlash(char *mess, ssize_t fsize, FILE *flashfd, FILE *srcfd) {
LOG(logDEBUG1, ("writing to flash\n"));
char *buffer = malloc(FLASH_BUFFER_MEMORY_SIZE);
if (buffer == NULL) {
fclose(flashfd);
fclose(srcfd);
sprintf(mess,
"Could not %s. Memory allocation to write to "
"flash failed.\n",
messageType);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tWriting to Flash...\n"));
int oldProgress = 0;
ssize_t totalBytes = 0;
ssize_t bytes =
fread((void *)buffer, sizeof(char), FLASH_BUFFER_MEMORY_SIZE, srcfd);
while (bytes > 0) {
ssize_t bytesWritten =
fwrite((void *)buffer, sizeof(char), bytes, flashfd);
totalBytes += bytesWritten;
if (bytesWritten != bytes) {
free(buffer);
fclose(flashfd);
fclose(srcfd);
sprintf(mess,
"Could not %s. Could not write to flash (bytes "
"written:%ld, expected: "
"%ld, total written:%ld)\n",
messageType, (long int)bytesWritten, (long int)bytes,
(long int)totalBytes);
LOG(logERROR, (mess));
return FAIL;
}
// print progress
if (fsize > 0) {
int progress = (int)(((double)(totalBytes) / fsize) * 100);
if (oldProgress != progress) {
printf("%d%%\r", progress);
fflush(stdout);
oldProgress = progress;
}
} else
printf(".");
bytes = fread((void *)buffer, sizeof(char), FLASH_BUFFER_MEMORY_SIZE,
srcfd);
}
if (fsize <= 0) {
printf("\n");
}
free(buffer);
fclose(flashfd);
fclose(srcfd);
LOG(logINFO, ("\tWrote %ld bytes to flash\n", totalBytes));
if (totalBytes != fsize) {
sprintf(mess,
"Could not %s. Incorrect bytes written to flash %lu "
"[expected: %lu]\n",
messageType, totalBytes, fsize);
LOG(logERROR, (mess));
return FAIL;
}
return OK;
}
int waitForFPGAtoTouchFlash(char *mess) {
// touch and program
if (FPGATouchFlash(mess) == FAIL) {
return FAIL;
}
#ifdef VIRTUAL
return OK;
#endif
LOG(logINFO, ("\tWaiting for FPGA to program from flash\n"));
int timeSpent = 0;
int result = 0;
while (result == 0) {
// time taken for fpga to pick up from flash
usleep(1000);
timeSpent += 1000;
if (timeSpent >= MAX_TIME_FPGA_TOUCH_FLASH_US) {
sprintf(
mess,
"Could not program fpga. (exceeded max time allowed: %ds)\n",
MAX_TIME_FPGA_TOUCH_FLASH_US / (1000 * 1000));
LOG(logERROR, (mess));
return FAIL;
}
// read gpio status
char retvals[MAX_STR_LENGTH] = {0};
if (FAIL ==
executeCommand(CMD_FPGA_PICKED_STATUS, retvals, logDEBUG1)) {
snprintf(
mess, MAX_STR_LENGTH,
"Could not program fpga. (could not read gpio status: %s)\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
}
// convert to int
if (sscanf(retvals, "%d\n", &result) != 1) {
snprintf(mess, MAX_STR_LENGTH,
"Could not program fpga. (could not scan int for gpio "
"status: [%s])\n",
retvals);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logDEBUG1, ("gpi07 returned %d\n", result));
}
LOG(logINFO, ("\tFPGA has picked up the program from flash\n"));
return OK;
}

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
#include "programFpgaNios.h"
#include "programViaNios.h"
#include "clogger.h"
#include "common.h"
#include "sls/ansi.h"
@ -11,10 +11,19 @@
/* global variables */
#define CMD_GET_FLASH "awk \'$5== \"Application\" {print $1}\' /proc/mtd"
#define CMD_GET_FPGA_FLASH_DRIVE \
"awk \'$5== \"Application\" {print $1}\' /proc/mtd"
#define CMD_GET_KERNEL_FLASH_DRIVE \
"awk \'$5== \"Linux\" && $9 != \"Backup\\\"\" {print $1}\' /proc/mtd"
#define FLASH_DRIVE_NAME_SIZE 16
#ifdef VIRTUAL
char flashDriveName[FLASH_DRIVE_NAME_SIZE] = "/tmp/SLS_mtd3";
#else
char flashDriveName[FLASH_DRIVE_NAME_SIZE] = {0};
#endif
char messageType[SHORT_STR_LENGTH] = {0};
#define MICROCONTROLLER_FILE "/dev/ttyAL0"
extern int executeCommand(char *command, char *result, enum TLogLevel level);
@ -35,19 +44,19 @@ void rebootControllerAndFPGA() {
system(command);
}
int eraseAndWriteToFlash(char *mess, char *checksum, char *fpgasrc,
int eraseAndWriteToFlash(char *mess, enum PROGRAM_INDEX index,
char *functionType, char *checksum, char *fpgasrc,
uint64_t fsize) {
if (verifyChecksumFromBuffer(mess, checksum, fpgasrc, fsize) == FAIL) {
return FAIL;
}
memset(messageType, 0, sizeof(messageType));
strcpy(messageType, functionType);
if (getDrive(mess) == FAIL) {
if (getDrive(mess, index) == FAIL) {
return FAIL;
}
FILE *flashfd = NULL;
if (openFileForFlash(&flashfd, mess) == FAIL) {
if (openFileForFlash(mess, &flashfd) == FAIL) {
return FAIL;
}
@ -56,21 +65,33 @@ int eraseAndWriteToFlash(char *mess, char *checksum, char *fpgasrc,
return FAIL;
}
if (writeToFlash(fsize, flashfd, fpgasrc, mess) == FAIL) {
if (writeToFlash(mess, fsize, flashfd, fpgasrc) == FAIL) {
return FAIL;
}
/* ignoring this until a consistent way to read from nios flash
if (verifyChecksumFromFlash(mess, checksum, flashDriveName, fsize) ==
FAIL) {
return FAIL;
/* remove condition when flash fpga fixed */
if (index == PROGRAM_KERNEL) {
if (verifyChecksumFromFlash(mess, messageType, checksum, flashDriveName,
fsize) == FAIL) {
return FAIL;
}
}
*/
if (index == PROGRAM_KERNEL) {
char retvals[MAX_STR_LENGTH] = {0};
if (executeCommand("sync", retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not update %s. (could not sync)\n", messageType);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
}
}
return OK;
}
int getDrive(char *mess) {
int getDrive(char *mess, enum PROGRAM_INDEX index) {
#ifdef VIRTUAL
strcpy(flashDriveName, "/tmp/SLS_mtd3");
return OK;
#endif
LOG(logDEBUG1, ("Finding flash drive...\n"));
@ -86,18 +107,33 @@ int getDrive(char *mess) {
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
strcpy(cmd, CMD_GET_FLASH);
if (index == PROGRAM_FPGA) {
strcpy(cmd, CMD_GET_FPGA_FLASH_DRIVE);
} else {
strcpy(cmd, CMD_GET_KERNEL_FLASH_DRIVE);
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not program fpga. (could not get flash drive: %s)\n",
"Could not %s. (could not get flash drive: %s)\n", messageType,
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
}
if (strlen(retvals) == 0) {
LOG(logERROR, ("Could not %s. Could not get mtd drive, script returned "
"empty string\n",
messageType));
return FAIL;
}
char *pch = strtok(retvals, ":");
if (pch == NULL) {
strcpy(mess, "Could not get mtd drive to flash (strtok fail).\n");
sprintf(
mess,
"Could not %s. Could not get mtd drive to flash (strtok fail).\n",
messageType);
LOG(logERROR, (mess));
return FAIL;
}
@ -109,11 +145,12 @@ int getDrive(char *mess) {
return OK;
}
int openFileForFlash(FILE **flashfd, char *mess) {
int openFileForFlash(char *mess, FILE **flashfd) {
*flashfd = fopen(flashDriveName, "w");
if (*flashfd == NULL) {
sprintf(mess, "Unable to open flash drive %s in write mode\n",
flashDriveName);
sprintf(mess,
"Could not %s. Unable to open flash drive %s in write mode\n",
messageType, flashDriveName);
LOG(logERROR, (mess));
return FAIL;
}
@ -130,17 +167,16 @@ int eraseFlash(char *mess) {
char cmd[MAX_STR_LENGTH] = {0};
char retvals[MAX_STR_LENGTH] = {0};
char *format = "flash_erase %s 0 0";
if (snprintf(cmd, MAX_STR_LENGTH, format, flashDriveName) >=
if (snprintf(cmd, MAX_STR_LENGTH, "flash_erase %s 0 0", flashDriveName) >=
MAX_STR_LENGTH) {
strcpy(mess,
"Could not program fpga. Command to erase flash is too long\n");
sprintf(mess, "Could not %s. Command to erase flash is too long\n",
messageType);
LOG(logERROR, (mess));
return FAIL;
}
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
snprintf(mess, MAX_STR_LENGTH,
"Could not program fpga. (could not erase flash: %s)\n",
"Could not %s. (could not erase flash: %s)\n", messageType,
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
return FAIL;
@ -150,19 +186,20 @@ int eraseFlash(char *mess) {
return OK;
}
int writeToFlash(ssize_t fsize, FILE *flashfd, char *buffer, char *mess) {
int writeToFlash(char *mess, ssize_t fsize, FILE *flashfd, char *buffer) {
LOG(logINFO, ("\tWriting to Flash...\n"));
ssize_t bytesWritten = fwrite((void *)buffer, sizeof(char), fsize, flashfd);
if (bytesWritten != fsize) {
fclose(flashfd);
sprintf(mess,
"Could not program fpga. Incorrect bytes written to flash %lu "
"Could not %s. Incorrect bytes written to flash %lu "
"[expected: %lu]\n",
(long int)bytesWritten, (long int)fsize);
messageType, (long int)bytesWritten, (long int)fsize);
LOG(logERROR, (mess));
return FAIL;
}
LOG(logINFO, ("\tWritten to Flash\n"));
fclose(flashfd);
LOG(logINFO, ("\tWrote %ld bytes to flash\n", bytesWritten));
return OK;
}

View File

@ -4,6 +4,7 @@
The port number is passed as an argument */
#include "clogger.h"
#include "common.h"
#include "communication_funcs.h"
#include "sharedMemory.h"
#include "sls/sls_detector_defs.h"
@ -150,7 +151,7 @@ int main(int argc, char *argv[]) {
break;
case 'u':
LOG(logINFO, ("Detected update mode\n"));
LOG(logINFO, ("Detected update mode from command line\n"));
updateFlag = 1;
break;
@ -185,6 +186,24 @@ int main(int argc, char *argv[]) {
if (sharedMemory_create(portno) == FAIL) {
return -1;
}
if (updateFlag == 0) {
// update flag if update file exists (command line arg overwrites)
const int fileNameSize = 128;
char fname[fileNameSize];
if (getAbsPath(fname, fileNameSize, UPDATE_FILE) == FAIL) {
LOG(logERROR,
("Could not get abs path to check if update file exists. "
"Will try current folder instead.\n"));
strcpy(fname, UPDATE_FILE);
}
if (access(fname, F_OK) == 0) {
updateFlag = 1;
LOG(logINFOBLUE, ("File Found: Update Mode enabled\n"));
} else {
LOG(logINFOBLUE, ("File not Found: Update Mode diabled\n"));
}
}
#ifdef STOP_SERVER
// start stop server process
char cmd[MAX_STR_LENGTH];
@ -193,7 +212,7 @@ int main(int argc, char *argv[]) {
memset(portCmd, 0, 256);
sprintf(portCmd, "-p%d", portno);
for (int i = 0; i < argc; ++i) {
LOG(logINFOBLUE, ("i:%d argv[i]:%s\n", i, argv[i]));
LOG(logDEBUG, ("i:%d argv[i]:%s\n", i, argv[i]));
// remove port argument (--port) and [value]
if (!strcasecmp(argv[i], "--port")) {
++i;

View File

@ -77,6 +77,42 @@ char scanErrMessage[MAX_STR_LENGTH] = "";
/* initialization functions */
int updateModeAllowedFunction(int file_des) {
unsigned int listsize = 19;
enum detFuncs list[] = {F_EXEC_COMMAND,
F_GET_DETECTOR_TYPE,
F_GET_FIRMWARE_VERSION,
F_GET_SERVER_VERSION,
F_GET_SERIAL_NUMBER,
F_WRITE_REGISTER,
F_READ_REGISTER,
F_LOCK_SERVER,
F_GET_LAST_CLIENT_IP,
F_PROGRAM_FPGA,
F_RESET_FPGA,
F_CHECK_VERSION,
F_COPY_DET_SERVER,
F_REBOOT_CONTROLLER,
F_GET_KERNEL_VERSION,
F_UPDATE_KERNEL,
F_UPDATE_DETECTOR_SERVER,
F_GET_UPDATE_MODE,
F_SET_UPDATE_MODE};
for (unsigned int i = 0; i < listsize; ++i) {
if ((unsigned int)fnum == list[i]) {
return OK;
}
}
ret = FAIL;
sprintf(mess,
"Funcion (%s) cannot be executed in update mode. Please disable "
"update mode to continue.\n",
getFunctionNameFromEnum((enum detFuncs)fnum));
LOG(logERROR, (mess));
Server_SendResult(file_des, INT32, NULL, 0);
return FAIL;
}
int printSocketReadError() {
LOG(logERROR, ("Error reading from socket. Possible socket crash.\n"));
return FAIL;
@ -92,14 +128,13 @@ void init_detector() {
#ifdef EIGERD
udpDetails[0].dstport2 = DEFAULT_UDP_DST_PORTNO + 1;
#endif
lockStatus = 0;
if (isControlServer) {
basictests();
initControlServer();
} else
} else {
initStopServer();
strcpy(mess, "dummy message");
lockStatus = 0;
}
}
int decode_function(int file_des) {
@ -118,6 +153,13 @@ int decode_function(int file_des) {
LOG(logERROR, ("Unknown function enum %d\n", fnum));
ret = (M_nofunc)(file_des);
} else {
// udpate mode restricted functions, send error (without waitin for
// arguments)
if (updateFlag && updateModeAllowedFunction(file_des) == FAIL) {
return FAIL;
}
LOG(logDEBUG1, (" calling function fnum=%d, (%s)\n", fnum,
getFunctionNameFromEnum((enum detFuncs)fnum)));
ret = (*flist[fnum])(file_des);
@ -414,6 +456,12 @@ void function_table() {
flist[F_SET_UDP_FIRST_DEST] = &set_udp_first_dest;
flist[F_GET_READOUT_SPEED] = &get_readout_speed;
flist[F_SET_READOUT_SPEED] = &set_readout_speed;
flist[F_GET_KERNEL_VERSION] = &get_kernel_version;
flist[F_UPDATE_KERNEL] = &update_kernel;
flist[F_UPDATE_DETECTOR_SERVER] = &update_detector_server;
flist[F_GET_UPDATE_MODE] = &get_update_mode;
flist[F_SET_UPDATE_MODE] = &set_update_mode;
// check
if (NUM_DET_FUNCTIONS >= RECEIVER_ENUM_START) {
LOG(logERROR, ("The last detector function enum has reached its "
@ -442,6 +490,9 @@ void modeNotImplemented(char *modename, int mode) {
}
int executeCommand(char *command, char *result, enum TLogLevel level) {
ret = OK;
memset(mess, 0, sizeof(mess));
const size_t tempsize = 256;
char temp[tempsize];
memset(temp, 0, tempsize);
@ -466,29 +517,26 @@ int executeCommand(char *command, char *result, enum TLogLevel level) {
memset(temp, 0, tempsize);
}
result[MAX_STR_LENGTH - 1] = '\0';
int success = pclose(sysFile);
if (strlen(result)) {
if (success) {
success = FAIL;
LOG(logERROR, ("%s\n", result));
} else {
LOG(level, ("Result:\n[%s]\n", result));
}
} else {
LOG(level, ("No result\n"));
if (strlen(result) == 0) {
strcpy(result, "No result");
}
return success;
int retval = OK;
int success = pclose(sysFile);
if (success) {
retval = FAIL;
LOG(logERROR, ("Executing cmd[%s]:%s\n", cmd, result));
} else {
LOG(level, ("Result:\n[%s]\n", result));
}
return retval;
}
int M_nofunc(int file_des) {
ret = FAIL;
memset(mess, 0, sizeof(mess));
// to receive any arguments
int n = 1;
while (n > 0)
n = receiveData(file_des, mess, MAX_STR_LENGTH, OTHER);
sprintf(mess, "Unrecognized Function enum %d. Please do not proceed.\n",
fnum);
LOG(logERROR, (mess));
@ -1559,15 +1607,8 @@ int set_module(int file_des) {
}
}
// receive all arguments
if (ret == FAIL) {
int n = 1;
while (n > 0)
n = receiveData(file_des, mess, MAX_STR_LENGTH, OTHER);
}
// only set
else if (Server_VerifyLock() == OK) {
if (ret == OK && Server_VerifyLock() == OK) {
// check index
// setsettings
@ -3639,149 +3680,10 @@ int program_fpga(int file_des) {
memset(mess, 0, sizeof(mess));
#if defined(EIGERD) || defined(GOTTHARDD)
// to receive any arguments
int n = 1;
while (n > 0)
n = receiveData(file_des, mess, MAX_STR_LENGTH, OTHER);
functionNotImplemented();
return Server_SendResult(file_des, INT32, NULL, 0);
#else
// only set
if (Server_VerifyLock() == OK) {
LOG(logINFOBLUE, ("Programming FPGA...\n"));
// filesize
uint64_t filesize = 0;
if (receiveData(file_des, &filesize, sizeof(filesize), INT64) < 0)
return printSocketReadError();
LOG(logDEBUG1, ("Program size is: %lld\n", (long long int)filesize));
// checksum
char checksum[MAX_STR_LENGTH];
memset(checksum, 0, MAX_STR_LENGTH);
if (receiveData(file_des, checksum, MAX_STR_LENGTH, OTHER) < 0)
return printSocketReadError();
LOG(logDEBUG1, ("checksum is: %s\n\n", checksum));
#if defined(MYTHEN3D) || defined(GOTTHARD2D)
if (filesize > NIOS_MAX_APP_IMAGE_SIZE) {
ret = FAIL;
sprintf(mess,
"Could not start programming FPGA. File size 0x%llx "
"exceeds max size 0x%llx. Forgot Compression?\n",
(long long unsigned int)filesize,
(long long unsigned int)NIOS_MAX_APP_IMAGE_SIZE);
LOG(logERROR, (mess));
}
Server_SendResult(file_des, INT32, NULL, 0);
// receive program
if (ret == OK) {
char *fpgasrc = malloc(filesize);
if (receiveData(file_des, fpgasrc, filesize, OTHER) < 0) {
free(fpgasrc);
return printSocketReadError();
}
ret = eraseAndWriteToFlash(mess, checksum, fpgasrc, filesize);
Server_SendResult(file_des, INT32, NULL, 0);
free(fpgasrc);
}
if (ret == FAIL) {
LOG(logERROR, ("Program FPGA FAIL!\n"));
return FAIL;
}
#else // jungfrau, ctb, moench
// open file and allocate memory for part program
FILE *fd = NULL;
ret = preparetoCopyFPGAProgram(&fd, filesize, mess);
char *src = NULL;
if (ret == OK) {
src = malloc(MAX_FPGAPROGRAMSIZE);
if (src == NULL) {
fclose(fd);
struct sysinfo info;
sysinfo(&info);
sprintf(mess,
"Could not allocate memory to get fpga program. Free "
"space: %d MB\n",
(int)(info.freeram / (1024 * 1024)));
LOG(logERROR, (mess));
ret = FAIL;
}
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
LOG(logERROR, ("Program FPGA FAIL1!\n"));
return FAIL;
}
// copying program part by part
uint64_t totalsize = filesize;
while (ret == OK && filesize) {
uint64_t unitprogramsize = MAX_FPGAPROGRAMSIZE; // 2mb
if (unitprogramsize > filesize) // less than 2mb
unitprogramsize = filesize;
LOG(logDEBUG1, ("unit size to receive is:%lld [filesize:%lld]\n",
(long long unsigned int)unitprogramsize,
(long long unsigned int)filesize));
// receive part of program
if (receiveData(file_des, src, unitprogramsize, OTHER) < 0) {
printSocketReadError();
break;
}
if (unitprogramsize - filesize == 0) {
// src[unitprogramsize] = '\0';
filesize -= unitprogramsize;
// unitprogramsize++;
} else
filesize -= unitprogramsize;
// copy program
if (fwrite((void *)src, sizeof(char), unitprogramsize, fd) !=
unitprogramsize) {
ret = FAIL;
sprintf(mess, "Could not copy program to /var/tmp (size:%ld)\n",
(long int)unitprogramsize);
LOG(logERROR, (mess));
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
break;
}
// print progress
LOG(logINFO,
("\t%d%%\r",
(int)(((double)(totalsize - filesize) / totalsize) * 100)));
fflush(stdout);
}
free(src);
fclose(fd);
// checksum of copied program
if (ret == OK) {
ret = verifyChecksumFromFile(mess, checksum, TEMP_PROG_FILE_NAME);
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
LOG(logERROR, ("Program FPGA FAIL!\n"));
return FAIL;
}
// copy to flash
ret = copyToFlash(totalsize, checksum, mess);
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
LOG(logERROR, ("Program FPGA FAIL!\n"));
return FAIL;
}
#endif // end of Blackfin programming
LOG(logINFOGREEN, ("Programming FPGA completed successfully\n"));
}
receive_program(file_des, PROGRAM_FPGA);
#endif
return ret;
}
@ -3799,9 +3701,25 @@ int reset_fpga(int file_des) {
if (Server_VerifyLock() == OK) {
if (isControlServer) {
basictests(); // mapping of control server at least
initControlServer();
} else
char *message = NULL;
if (getInitResult(&message) == FAIL) {
ret = FAIL;
strcpy(mess, message);
LOG(logERROR, (mess));
} else {
initControlServer();
}
} else {
initStopServer(); // remapping of stop server
}
if (ret == OK) {
char *message = NULL;
if (getInitResult(&message) == FAIL) {
ret = FAIL;
strcpy(mess, message);
LOG(logERROR, (mess));
}
}
}
#endif
return Server_SendResult(file_des, INT32, NULL, 0);
@ -4225,113 +4143,33 @@ int copy_detector_server(int file_des) {
LOG(logINFOBLUE, ("Copying server %s from host %s\n", sname, hostname));
char cmd[MAX_STR_LENGTH] = {0};
// tftp server
char *format = "tftp %s -r %s -g";
if (snprintf(cmd, MAX_STR_LENGTH, format, hostname, sname) >=
MAX_STR_LENGTH) {
ret = FAIL;
strcpy(mess, "Could not copy detector server. Command to copy "
"server too long\n");
LOG(logERROR, (mess));
} else if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
ret = FAIL;
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (tftp). %s\n", retvals);
// LOG(logERROR, (mess)); already printed in executecommand
} else {
LOG(logINFO, ("\tServer copied\n"));
}
// give permissions
if (ret == OK) {
if (snprintf(cmd, MAX_STR_LENGTH, "chmod 777 %s", sname) >=
MAX_STR_LENGTH) {
ret = FAIL;
strcpy(mess, "Could not copy detector server. Command to give "
"permissions to server is too long\n");
LOG(logERROR, (mess));
} else if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
ret = FAIL;
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (permissions). %s\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
} else {
LOG(logINFO, ("\tPermissions modified\n"));
}
}
// symbolic link
if (ret == OK) {
if (snprintf(cmd, MAX_STR_LENGTH, "ln -sf %s %s", sname,
LINKED_SERVER_NAME) >= MAX_STR_LENGTH) {
ret = FAIL;
strcpy(mess, "Could not copy detector server. Command to "
"create symbolic link too long\n");
LOG(logERROR, (mess));
} else if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
ret = FAIL;
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (symbolic link). %s\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
} else {
LOG(logINFO, ("\tSymbolic link created\n"));
}
}
// blackfin boards (respawn) (only kept for backwards compatibility)
#if defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) || \
defined(GOTTHARDD)
// delete every line with DetectorServer in /etc/inittab
if (ret == OK) {
strcpy(cmd, "sed -i '/DetectorServer/d' /etc/inittab");
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
ret = FAIL;
snprintf(
mess, MAX_STR_LENGTH,
"Could not copy detector server (del respawning). %s\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
} else {
LOG(logINFO, ("\tinittab: DetectoServer line deleted\n"));
}
}
// add new link name to /etc/inittab
if (ret == OK) {
format = "echo 'ttyS0::respawn:/./%s' >> /etc/inittab";
if (snprintf(cmd, MAX_STR_LENGTH, format, LINKED_SERVER_NAME) >=
MAX_STR_LENGTH) {
ret = FAIL;
strcpy(mess, "Could not copy detector server. Command "
"to add new server for spawning is too long\n");
LOG(logERROR, (mess));
} else if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
ret = FAIL;
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (respawning). %s\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
} else {
LOG(logINFO, ("\tinittab: updated for respawning\n"));
}
}
#ifdef BLACKFIN_DEFINED
// check update is allowed (Non Amd OR AMD + current kernel)
ret = allowUpdate(mess, "copy detector server");
#endif
// sync
// tftp server
if (ret == OK) {
strcpy(cmd, "sync");
if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
if (snprintf(cmd, MAX_STR_LENGTH, "tftp %s -r %s -g", hostname,
sname) >= MAX_STR_LENGTH) {
ret = FAIL;
strcpy(mess, "Could not copy detector server. Command to copy "
"server too long\n");
LOG(logERROR, (mess));
} else if (executeCommand(cmd, retvals, logDEBUG1) == FAIL) {
ret = FAIL;
snprintf(mess, MAX_STR_LENGTH,
"Could not copy detector server (sync). %s\n",
"Could not copy detector server (tftp). %s\n",
retvals);
// LOG(logERROR, (mess)); already printed in executecommand
} else {
LOG(logINFO, ("\tsync\n"));
LOG(logINFO, ("\tServer copied\n"));
}
}
if (ret == OK) {
ret = setupDetectorServer(mess, sname);
}
}
#endif
return Server_SendResult(file_des, OTHER, retvals, sizeof(retvals));
@ -4825,6 +4663,13 @@ int set_read_n_rows(int file_des) {
"of %d\n",
arg, READ_N_ROWS_MULTIPLE);
LOG(logERROR, (mess));
}
// only for HW 2.0 (version = 3)
else if (isHardwareVersion2()) {
ret = FAIL;
strcpy(mess, "Could not set number of rows. Only available for "
"Hardware Board version 2.0.\n");
LOG(logERROR, (mess));
} else
#endif
{
@ -4860,11 +4705,10 @@ int get_read_n_rows(int file_des) {
#if !defined(EIGERD) && !defined(JUNGFRAUD)
functionNotImplemented();
#else
// get only
retval = getReadNRows();
if (retval == -1) {
ret = FAIL;
sprintf(mess, "Could not get numbr of rows. \n");
sprintf(mess, "Could not get number of rows. \n");
LOG(logERROR, (mess));
} else {
LOG(logDEBUG1, ("number of rows retval: %u\n", retval));
@ -8837,8 +8681,16 @@ int get_flip_rows(int file_des) {
functionNotImplemented();
#else
// get only
retval = getFlipRows();
LOG(logDEBUG1, ("flip rows retval: %u\n", retval));
// only for HW 2.0 (version = 3)
if (isHardwareVersion2()) {
ret = FAIL;
strcpy(mess, "Could not get flip rows. Only available for "
"Hardware Board version 2.0.\n");
LOG(logERROR, (mess));
} else {
retval = getFlipRows();
LOG(logDEBUG1, ("flip rows retval: %u\n", retval));
}
#endif
return Server_SendResult(file_des, INT32, &retval, sizeof(retval));
}
@ -8897,8 +8749,16 @@ int get_num_filter_cells(int file_des) {
functionNotImplemented();
#else
// get only
retval = getNumberOfFilterCells();
LOG(logDEBUG1, ("num filter cells retval: %u\n", retval));
// only for chipv1.1
if (getChipVersion() == 10) {
ret = FAIL;
strcpy(mess, "Could not get number of filter cells. Only available for "
"chip version 1.1\n");
LOG(logERROR, (mess));
} else {
retval = getNumberOfFilterCells();
LOG(logDEBUG1, ("num filter cells retval: %u\n", retval));
}
#endif
return Server_SendResult(file_des, INT32, &retval, sizeof(retval));
}
@ -9410,5 +9270,388 @@ int set_readout_speed(int file_des) {
}
}
#endif
return Server_SendResult(file_des, INT32, NULL, 0);
}
int get_kernel_version(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
char retvals[MAX_STR_LENGTH];
memset(retvals, 0, MAX_STR_LENGTH);
LOG(logDEBUG1, ("Getting kernel version\n"));
// get only
ret = getKernelVersion(retvals);
if (ret == FAIL) {
if (snprintf(mess, MAX_STR_LENGTH, "Could not get kernel version. %s\n",
retvals) >= MAX_STR_LENGTH) {
ret = FAIL;
strcpy(mess,
"Could not get kernel version. Reason too long to copy\n");
}
LOG(logERROR, (mess));
} else {
LOG(logDEBUG1, ("kernel version: [%s]\n", retvals));
}
return Server_SendResult(file_des, OTHER, retvals, sizeof(retvals));
}
int update_kernel(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
#ifdef EIGERD
functionNotImplemented();
return Server_SendResult(file_des, INT32, NULL, 0);
#else
receive_program(file_des, PROGRAM_KERNEL);
#endif
return ret;
}
int update_detector_server(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
return receive_program(file_des, PROGRAM_SERVER);
}
int receive_program(int file_des, enum PROGRAM_INDEX index) {
// only set
if (Server_VerifyLock() == OK) {
char functionType[SHORT_STR_LENGTH] = {0};
switch (index) {
case PROGRAM_FPGA:
strcpy(functionType, "Update Firmware");
break;
case PROGRAM_KERNEL:
strcpy(functionType, "Update Kernel");
break;
case PROGRAM_SERVER:
strcpy(functionType, "Update Server");
break;
}
LOG(logINFOBLUE, ("%s ...\n", functionType));
// filesize
uint64_t filesize = 0;
if (receiveData(file_des, &filesize, sizeof(filesize), INT64) < 0)
return printSocketReadError();
LOG(logINFO, ("\tProgram size: %lld\n", (long long int)filesize));
// client checksum
char checksum[MAX_STR_LENGTH] = {0};
if (receiveData(file_des, checksum, MAX_STR_LENGTH, OTHER) < 0)
return printSocketReadError();
LOG(logINFO, ("\tChecksum: %s\n", checksum));
// server name
char serverName[MAX_STR_LENGTH] = {0};
if (index == PROGRAM_SERVER) {
if (receiveData(file_des, serverName, MAX_STR_LENGTH, OTHER) < 0)
return printSocketReadError();
LOG(logINFO, ("\tServer Name: %s\n", serverName));
}
// in same folder as current process (will also work for virtual then
// with write permissions)
{
const int fileNameSize = 128;
char fname[fileNameSize];
if (getAbsPath(fname, fileNameSize, serverName) == FAIL) {
ret = FAIL;
sprintf(mess,
"Could not %s. Could not get abs path of current "
"process\n",
functionType);
LOG(logERROR, (mess));
Server_SendResult(file_des, INT32, NULL, 0);
} else {
strcpy(serverName, fname);
}
}
if (ret == OK) {
#if defined(GOTTHARD2D) || defined(MYTHEN3D) || defined(EIGERD)
receive_program_default(file_des, index, functionType, filesize,
checksum, serverName);
#else
receive_program_via_blackfin(file_des, index, functionType,
filesize, checksum, serverName);
#endif
}
if (ret == OK) {
LOG(logINFOGREEN, ("%s completed successfully\n", functionType));
} else {
LOG(logERROR, ("%s FAIL!\n", functionType));
}
}
return ret;
}
void receive_program_via_blackfin(int file_des, enum PROGRAM_INDEX index,
char *functionType, uint64_t filesize,
char *checksum, char *serverName) {
#if !defined(JUNGFRAUD) && !defined(CHIPTESTBOARDD) && !defined(MOENCHD) && \
!defined(GOTTHARDD)
ret = FAIL;
sprintf(mess,
"Could not %s. program via blackfin not implmented for this "
"detector.\n",
functionType);
LOG(logERROR, (mess));
#else
// only when writing to kernel flash or root directory
if (index != PROGRAM_FPGA) {
// check update is allowed (Non Amd OR AMD + current kernel)
ret = allowUpdate(mess, functionType);
if (ret == FAIL) {
Server_SendResult(file_des, INT32, NULL, 0);
return;
}
}
// open file and allocate memory for part program
FILE *fd = NULL;
ret = preparetoCopyProgram(mess, functionType, &fd, filesize);
char *src = NULL;
if (ret == OK) {
src = malloc(MAX_BLACKFIN_PROGRAM_SIZE);
if (src == NULL) {
fclose(fd);
struct sysinfo info;
sysinfo(&info);
sprintf(mess,
"Could not %s. Memory allocation failure. Free "
"space: %d MB\n",
functionType, (int)(info.freeram / (1024 * 1024)));
LOG(logERROR, (mess));
ret = FAIL;
}
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
return;
}
// copying program part by part
uint64_t totalsize = filesize;
while (ret == OK && filesize) {
uint64_t unitprogramsize = MAX_BLACKFIN_PROGRAM_SIZE;
if (unitprogramsize > filesize)
unitprogramsize = filesize;
LOG(logDEBUG1, ("unit size to receive is:%lld [filesize:%lld]\n",
(long long unsigned int)unitprogramsize,
(long long unsigned int)filesize));
// receive part of program
if (receiveData(file_des, src, unitprogramsize, OTHER) < 0) {
printSocketReadError();
break;
}
filesize -= unitprogramsize;
// copy program
if (fwrite((void *)src, sizeof(char), unitprogramsize, fd) !=
unitprogramsize) {
ret = FAIL;
sprintf(
mess,
"Could not %s. Could not copy program to /var/tmp (size:%ld)\n",
functionType, (long int)unitprogramsize);
LOG(logERROR, (mess));
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
break;
}
// print progress
LOG(logINFO,
("\t%d%%\r",
(int)(((double)(totalsize - filesize) / totalsize) * 100)));
fflush(stdout);
}
free(src);
fclose(fd);
// checksum of copied program
if (ret == OK) {
ret = verifyChecksumFromFile(mess, functionType, checksum,
TEMP_PROG_FILE_NAME);
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
return;
}
// appropriate functions
switch (index) {
case PROGRAM_FPGA:
case PROGRAM_KERNEL:
ret = eraseAndWriteToFlash(mess, index, functionType, checksum,
totalsize);
break;
case PROGRAM_SERVER:
ret = moveBinaryFile(mess, serverName, TEMP_PROG_FILE_NAME,
"update detector server");
if (ret == OK) {
ret = setupDetectorServer(mess, serverName);
}
break;
default:
modeNotImplemented("Program index", (int)index);
break;
}
// erase and copy to flash
Server_SendResult(file_des, INT32, NULL, 0);
#endif
}
void receive_program_default(int file_des, enum PROGRAM_INDEX index,
char *functionType, uint64_t filesize,
char *checksum, char *serverName) {
#if !defined(GOTTHARD2D) && !defined(MYTHEN3D) && !defined(EIGERD)
ret = FAIL;
sprintf(mess,
"Could not %s. program via blackfin not implmented for this "
"detector.\n",
functionType);
LOG(logERROR, (mess))
#else
#if defined(GOTTHARD2D) || defined(MYTHEN3D)
// validate file size
if (filesize > NIOS_MAX_APP_IMAGE_SIZE) {
ret = FAIL;
sprintf(mess,
"Could not %s. File size 0x%llx "
"exceeds max size 0x%llx. Forgot Compression?\n",
functionType, (long long unsigned int)filesize,
(long long unsigned int)NIOS_MAX_APP_IMAGE_SIZE);
LOG(logERROR, (mess));
}
#endif
// memory allocation
char *src = NULL;
if (ret == OK) {
src = malloc(filesize);
if (src == NULL) {
struct sysinfo info;
sysinfo(&info);
sprintf(mess,
"Could not %s. Memory allocation failure. Free "
"space: %d MB\n",
functionType, (int)(info.freeram / (1024 * 1024)));
LOG(logERROR, (mess));
ret = FAIL;
}
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
return;
}
// receive program
if (receiveData(file_des, src, filesize, OTHER) < 0) {
free(src);
ret = printSocketReadError();
return;
}
// checksum of copied program
if (ret == OK) {
ret = verifyChecksumFromBuffer(mess, functionType, checksum, src,
filesize);
}
Server_SendResult(file_des, INT32, NULL, 0);
if (ret == FAIL) {
return;
}
// appropriate functions
switch (index) {
#if defined(GOTTHARD2D) || defined(MYTHEN3D)
case PROGRAM_FPGA:
case PROGRAM_KERNEL:
ret = eraseAndWriteToFlash(mess, index, functionType, checksum, src,
filesize);
break;
#endif
#if defined(GOTTHARD2D) || defined(MYTHEN3D) || defined(EIGERD)
case PROGRAM_SERVER:
ret = writeBinaryFile(mess, TEMP_PROG_FILE_NAME, src, filesize,
"update detector server");
// extra step to write to temp and move to real file as
// fopen will give text busy if opening same name as process name
if (ret == OK) {
ret = moveBinaryFile(mess, serverName, TEMP_PROG_FILE_NAME,
"update detector server");
}
if (ret == OK) {
ret = verifyChecksumFromFile(mess, functionType, checksum,
serverName);
}
if (ret == OK) {
ret = setupDetectorServer(mess, serverName);
}
break;
#endif
default:
modeNotImplemented("Program index", (int)index);
break;
}
// send result
Server_SendResult(file_des, INT32, NULL, 0);
// free resources
free(src);
#endif
}
int get_update_mode(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
int retval = -1;
LOG(logDEBUG1, ("Getting update mode\n"));
retval = updateFlag;
LOG(logDEBUG1, ("update mode retval: %d\n", retval));
return Server_SendResult(file_des, INT32, &retval, sizeof(retval));
}
int set_update_mode(int file_des) {
ret = OK;
memset(mess, 0, sizeof(mess));
int arg = -1;
if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0)
return printSocketReadError();
LOG(logDEBUG1, ("Setting update mode to \n", arg));
#ifdef BLACKFIN_DEFINED
// check update is allowed (Non Amd OR AMD + current kernel)
ret = allowUpdate(mess, "set/unset update mode");
#endif
if (ret == OK) {
switch (arg) {
case 0:
ret = deleteFile(mess, UPDATE_FILE, "unset update mode");
break;
case 1:
ret = createEmptyFile(mess, UPDATE_FILE, "set update mode");
break;
default:
ret = FAIL;
sprintf(mess, "Could not set updatemode. Options: 0 or 1\n");
LOG(logERROR, (mess));
break;
}
}
return Server_SendResult(file_des, INT32, NULL, 0);
}

View File

@ -9,16 +9,16 @@ set(SOURCES
src/Pattern.cpp
)
add_library(slsDetectorStatic STATIC
add_library(slsDetectorObject OBJECT
${SOURCES}
)
target_include_directories(slsDetectorStatic PUBLIC
target_include_directories(slsDetectorObject PUBLIC
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
)
target_link_libraries(slsDetectorStatic
target_link_libraries(slsDetectorObject
PUBLIC
slsProjectOptions
slsSupportStatic
@ -28,7 +28,7 @@ target_link_libraries(slsDetectorStatic
slsProjectWarnings
)
set(DETECTOR_LIBRARY_TARGETS slsDetectorStatic)
set(DETECTOR_LIBRARY_TARGETS slsDetectorObject)
set(PUBLICHEADERS
@ -39,29 +39,29 @@ set(PUBLICHEADERS
)
#Shared library
# if(SLS_BUILD_SHARED_LIBRARIES)
# add_library(slsDetectorShared SHARED $<TARGET_OBJECTS:slsDetectorObject>)
# target_link_libraries(slsDetectorShared PUBLIC slsDetectorObject)
# set_target_properties(slsDetectorShared PROPERTIES
# VERSION ${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}.${PACKAGE_VERSION_PATCH}
# SOVERSION ${PACKAGE_VERSION_MAJOR}
# LIBRARY_OUTPUT_NAME SlsDetector
# LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
# PUBLIC_HEADER "${PUBLICHEADERS}"
# )
# list(APPEND DETECTOR_LIBRARY_TARGETS slsDetectorShared)
# endif(SLS_BUILD_SHARED_LIBRARIES)
if(SLS_BUILD_SHARED_LIBRARIES)
add_library(slsDetectorShared SHARED $<TARGET_OBJECTS:slsDetectorObject>)
target_link_libraries(slsDetectorShared PUBLIC slsDetectorObject)
set_target_properties(slsDetectorShared PROPERTIES
VERSION ${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}.${PACKAGE_VERSION_PATCH}
SOVERSION ${PACKAGE_VERSION_MAJOR}
LIBRARY_OUTPUT_NAME SlsDetector
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
PUBLIC_HEADER "${PUBLICHEADERS}"
)
list(APPEND DETECTOR_LIBRARY_TARGETS slsDetectorShared)
endif(SLS_BUILD_SHARED_LIBRARIES)
#Static library
# add_library(slsDetectorStatic STATIC $<TARGET_OBJECTS:slsDetectorObject>)
# target_link_libraries(slsDetectorStatic PUBLIC slsDetectorObject)
add_library(slsDetectorStatic STATIC $<TARGET_OBJECTS:slsDetectorObject>)
target_link_libraries(slsDetectorStatic PUBLIC slsDetectorObject)
set_target_properties(slsDetectorStatic PROPERTIES
ARCHIVE_OUTPUT_NAME SlsDetectorStatic
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
PUBLIC_HEADER "${PUBLICHEADERS}"
)
# list(APPEND DETECTOR_LIBRARY_TARGETS slsDetectorStatic)
list(APPEND DETECTOR_LIBRARY_TARGETS slsDetectorStatic)
@ -69,9 +69,6 @@ set_target_properties(slsDetectorStatic PROPERTIES
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET ${DETECTOR_LIBRARY_TARGETS} PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
# set_property(TARGET slsDetectorObject PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
# set_property(TARGET slsDetectorStatic PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
# set_property(TARGET slsDetectorShared PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()
@ -100,7 +97,7 @@ if(SLS_USE_TEXTCLIENT)
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
COMPILE_DEFINITIONS ${val2}=1
)
if(SLS_LTO_AVAILABLE)
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET ${val1} PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()
endforeach()

View File

@ -81,6 +81,8 @@ class Detector {
Result<int64_t> getDetectorServerVersion(Positions pos = {}) const;
Result<std::string> getKernelVersion(Positions pos = {}) const;
/* [Jungfrau][Gotthard][Mythen3][Gotthard2][CTB][Moench] */
Result<int64_t> getSerialNumber(Positions pos = {}) const;
@ -1731,7 +1733,8 @@ class Detector {
/** [Jungfrau][CTB][Moench] Advanced user Function! */
void resetFPGA(Positions pos = {});
/** [Jungfrau][Eiger][Gotthard][CTB][Moench][Mythen3][Gotthard2]
/** [[deprecated ("Replaced by updateDetectorServer, which does not require
* tftp")]] [Jungfrau][Eiger][Gotthard][CTB][Moench][Mythen3][Gotthard2]
* Advanced user Function! \n
* Copy detector server fname from tftp folder of hostname to detector. Also
* creates a symbolic link to a shorter name (without vx.x.x). Then the
@ -1742,22 +1745,55 @@ class Detector {
void copyDetectorServer(const std::string &fname,
const std::string &hostname, Positions pos = {});
/** [Jungfrau][Eiger][Ctb][Moench][Mythen3][Gotthard2] Copies detector
* server via TCP (without tftp).\nMakes a symbolic link with a shorter
* name (without vx.x.x).\nThen, detector controller reboots (except
* Eiger).\n[Jungfrau][Ctb][Moench]Also changes respawn server to the
* link, which is effective after a reboot.
*/
void updateDetectorServer(const std::string &fname, Positions pos = {});
/** [Jungfrau][Ctb][Moench][Mythen3][Gotthard2] \n
* Advanced Command!! You could damage the detector. Please use with
* caution.\nUpdates the kernel image. Then, detector controller reboots
* with new kernel
*/
void updateKernel(const std::string &fname, Positions pos = {});
/** [Jungfrau][Gotthard][CTB][Moench][Mythen3][Gotthard2] Advanced user
* Function! */
void rebootController(Positions pos = {});
/** [[deprecated ("Replaced by overloaded updateDetectorServer, which does
* not require tftp and has one less argument")]] Advanced user Function!\n
* [Jungfrau][Gotthard][CTB][Moench] Updates the firmware, detector server,
* make a soft link and then reboots detector controller. \n
* [Mythen3][Gotthard2] Will require a script to start up the shorter named
* server link at start up \n sname is name of detector server binary found
* on tftp folder of host pc \n hostname is name of pc to tftp from \n fname
* is programming file name with full path to it
*/
void updateFirmwareAndServer(const std::string &sname,
const std::string &hostname,
const std::string &fname, Positions pos = {});
/**
* Advanced user Function!\n [Jungfrau][Gotthard][CTB][Moench] Updates the
* firmware, detector server, make a soft link and then reboots detector
* controller. \n [Mythen3][Gotthard2] Will require a script to start up the
* shorter named server link at start up \n sname is name of detector
* server binary found on tftp folder of host pc \n hostname is name of pc
* to tftp from \n fname is programming file name with full path to it
* shorter named server link at start up \n sname is full path name of
* detector server \n fname is programming file name with full path to it
*/
void updateFirmwareAndServer(const std::string &sname,
const std::string &hostname,
const std::string &fname, Positions pos = {});
Result<bool> getUpdateMode(Positions pos = {}) const;
/** Restarts detector server in update mode. This is useful when
* server-firmware compatibility is at its worst and server cannot start up
* normally */
void setUpdateMode(const bool updatemode, Positions pos = {});
/** Advanced user Function! \n
* Goes to stop server. Hence, can be called while calling blocking
* acquire(). \n [Eiger] Address is +0x100 for only left, +0x200 for only

View File

@ -275,7 +275,7 @@ std::string CmdProxy::Versions(int action) {
if (!args.empty()) {
WrongNumberOfParameters(0);
}
auto t = det->getFirmwareVersion();
auto t = det->getFirmwareVersion(std::vector<int>{det_id});
os << "\nDetector Type: " << OutString(det->getDetectorType())
<< "\nPackage Version: " << det->getPackageVersion() << std::hex
<< "\nClient Version: 0x" << det->getClientVersion();
@ -285,10 +285,14 @@ std::string CmdProxy::Versions(int action) {
os << "\nFirmware Version: " << OutStringHex(t);
}
os << "\nDetector Server Version: "
<< OutStringHex(det->getDetectorServerVersion());
<< OutStringHex(
det->getDetectorServerVersion(std::vector<int>{det_id}));
os << "\nDetector Server Version: "
<< OutString(det->getKernelVersion({std::vector<int>{det_id}}));
if (det->getUseReceiverFlag().squash(true)) {
os << "\nReceiver Version: "
<< OutStringHex(det->getReceiverVersion());
<< OutStringHex(
det->getReceiverVersion(std::vector<int>{det_id}));
}
os << std::dec << '\n';
} else if (action == defs::PUT_ACTION) {
@ -1430,8 +1434,9 @@ std::string CmdProxy::UDPDestinationList(int action) {
throw sls::RuntimeError("udp_dstlist must be at module level.");
}
if (rx_id < 0 || rx_id >= MAX_UDP_DESTINATION) {
throw sls::RuntimeError(
"Invalid receiver index to get round robin entry.");
throw sls::RuntimeError(std::string("Invalid receiver index ") +
std::to_string(rx_id) +
std::string(" to set round robin entry."));
}
auto t = det->getDestinationUDPList(rx_id, std::vector<int>{det_id});
os << OutString(t) << '\n';
@ -2848,11 +2853,14 @@ std::string CmdProxy::CopyDetectorServer(int action) {
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
LOG(logWARNING) << "Deprecated! Replaced by updatedetectorserver that "
"requires no tftp.\n";
os << "[server_name (in tftp folder)] "
"[pc_host_name]\n\t[Jungfrau][Eiger][Ctb][Moench][Mythen3]["
"Gotthard2] Copies detector server via tftp from pc. Ensure that "
"Gotthard2] Copies detector server via TFTP from pc. Ensure that "
"server is in the pc's tftp folder. Makes a symbolic link with a "
"shorter name (without vx.x.x). Then, detector reboots (except "
"shorter name (without vx.x.x). Then, detector controller "
"reboots (except "
"Eiger).\n\t[Jungfrau][Ctb][Moench]Also changes respawn server "
"to the link, which is effective after a reboot."
<< '\n';
@ -2870,30 +2878,98 @@ std::string CmdProxy::CopyDetectorServer(int action) {
return os.str();
}
std::string CmdProxy::UpdateFirmwareAndDetectorServer(int action) {
std::string CmdProxy::UpdateDetectorServer(int action) {
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "[server_name (in tftp folder)] [pc_host_name] [fname.pof (incl "
"full path)]\n\t[Jungfrau][Gotthard][CTB][Moench] Updates the "
"firmware, detector server, creates the symbolic link and then "
"reboots detector controller. \n\t[Mythen3][Gotthard2] will "
"require a script to start up the shorter named server link at "
"start up. \n\tsname is name of detector server binary found on "
"tftp folder of host pc \n\thostname is name of pc to tftp from "
"\n\tfname is programming file name"
os << "[server_name with full "
"path]\n\t[Jungfrau][Eiger][Ctb][Moench][Mythen3]["
"Gotthard2] Copies detector server via TCP (without tftp). Makes "
"a symbolic link with a shorter name (without vx.x.x). Then, "
"detector controller reboots (except "
"Eiger).\n\t[Jungfrau][Ctb][Moench]Also changes respawn server "
"to the link, which is effective after a reboot."
<< '\n';
} else if (action == defs::GET_ACTION) {
throw sls::RuntimeError("Cannot get");
} else if (action == defs::PUT_ACTION) {
if (args.size() != 3) {
WrongNumberOfParameters(3);
if (args.size() != 1) {
WrongNumberOfParameters(1);
}
if (args[2].find(".pof") == std::string::npos) {
throw sls::RuntimeError("Programming file must be a pof file.");
det->updateDetectorServer(args[0], std::vector<int>{det_id});
os << "successful\n";
} else {
throw sls::RuntimeError("Unknown action");
}
return os.str();
}
std::string CmdProxy::UpdateKernel(int action) {
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "[kernel_name with full "
"path]\n\t[Jungfrau][Ctb][Moench][Mythen3]["
"Gotthard2] Advanced Command!! You could damage the detector. "
"Please use"
" with caution.\n\tUpdates the kernel image. Then, detector "
"controller "
"reboots with new kernel."
<< '\n';
} else if (action == defs::GET_ACTION) {
throw sls::RuntimeError("Cannot get");
} else if (action == defs::PUT_ACTION) {
if (args.size() != 1) {
WrongNumberOfParameters(1);
}
det->updateKernel(args[0], std::vector<int>{det_id});
os << "successful\n";
} else {
throw sls::RuntimeError("Unknown action");
}
return os.str();
}
std::string CmdProxy::UpdateFirmwareAndDetectorServer(int action) {
std::ostringstream os;
os << cmd << ' ';
if (action == defs::HELP_ACTION) {
os << "\n\tUsing tftp: Deprecated!! [server_name"
" (in tftp folder)] [pc_host_name] [fname.pof (incl full path)]"
"\n\tWithout tftp: Recommended [server_name (incl fullpath)] "
"[fname.pof (incl full path)] "
"This does not use tftp."
"\n\t\t[Jungfrau][Gotthard][CTB][Moench] Updates the "
"firmware, detector server, creates the symbolic link and then "
"reboots detector controller. \n\t\t[Mythen3][Gotthard2] will "
"require a script to start up the shorter named server link at "
"start up. \n\t\tsname is full path name of detector server "
"binary"
"\n\t\tfname is full path of programming file"
<< '\n';
} else if (action == defs::GET_ACTION) {
throw sls::RuntimeError("Cannot get");
} else if (action == defs::PUT_ACTION) {
if (args.size() != 3 && args.size() != 2) {
WrongNumberOfParameters(2);
}
int fpos = args.size() - 1;
if (args[fpos].find(".pof") == std::string::npos &&
args[fpos].find(".rbf") == std::string::npos) {
throw sls::RuntimeError("Programming file must be a pof/rbf file.");
}
if (args.size() == 3) {
LOG(logWARNING)
<< "Deprecated! Recommend to use same command without tftp (no "
"pc name) and using full path to the server binary";
det->updateFirmwareAndServer(args[0], args[1], args[2],
std::vector<int>{det_id});
} else {
det->updateFirmwareAndServer(args[0], args[1],
std::vector<int>{det_id});
}
det->updateFirmwareAndServer(args[0], args[1], args[2],
std::vector<int>{det_id});
os << "successful\n";
} else {
throw sls::RuntimeError("Unknown action");

View File

@ -767,6 +767,7 @@ class CmdProxy {
{"clientversion", &CmdProxy::ClientVersion},
{"firmwareversion", &CmdProxy::FirmwareVersion},
{"detectorserverversion", &CmdProxy::detectorserverversion},
{"kernelversion", &CmdProxy::kernelversion},
{"rx_version", &CmdProxy::rx_version},
{"serialnumber", &CmdProxy::serialnumber},
{"moduleid", &CmdProxy::moduleid},
@ -1058,8 +1059,11 @@ class CmdProxy {
{"programfpga", &CmdProxy::ProgramFpga},
{"resetfpga", &CmdProxy::resetfpga},
{"copydetectorserver", &CmdProxy::CopyDetectorServer},
{"updatedetectorserver", &CmdProxy::UpdateDetectorServer},
{"updatekernel", &CmdProxy::UpdateKernel},
{"rebootcontroller", &CmdProxy::rebootcontroller},
{"update", &CmdProxy::UpdateFirmwareAndDetectorServer},
{"updatemode", &CmdProxy::updatemode},
{"reg", &CmdProxy::Register},
{"adcreg", &CmdProxy::AdcRegister},
{"setbit", &CmdProxy::BitOperations},
@ -1182,6 +1186,8 @@ class CmdProxy {
/* Advanced */
std::string ProgramFpga(int action);
std::string CopyDetectorServer(int action);
std::string UpdateDetectorServer(int action);
std::string UpdateKernel(int action);
std::string UpdateFirmwareAndDetectorServer(int action);
std::string Register(int action);
std::string AdcRegister(int action);
@ -1206,6 +1212,10 @@ class CmdProxy {
detectorserverversion, getDetectorServerVersion,
"\n\tOn-board detector server software version in format [0xYYMMDD].");
GET_COMMAND(
kernelversion, getKernelVersion,
"\n\tGet kernel version on the detector including time and date.");
GET_COMMAND_HEX(rx_version, getReceiverVersion,
"\n\tReceiver version in format [0xYYMMDD].");
@ -2175,6 +2185,12 @@ class CmdProxy {
"\n\t[Jungfrau][Ctb][Moench][Gotthard][Mythen3]["
"Gotthard2] Reboot controller of detector.");
INTEGER_COMMAND_VEC_ID(
updatemode, getUpdateMode, setUpdateMode, StringTo<int>,
"[0|1]\n\tRestart the detector server in update mode or not. This is "
"useful when server-firmware compatibility is at its worst and server "
"cannot start up normally");
EXECUTE_SET_COMMAND(
firmwaretest, executeFirmwareTest,
"\n\t[Jungfrau][Gotthard][Mythen3][Gotthard2][Ctb][Moench] Firmware "

View File

@ -9,6 +9,7 @@
#include "Module.h"
#include "sls/Pattern.h"
#include "sls/container_utils.h"
#include "sls/file_utils.h"
#include "sls/logger.h"
#include "sls/sls_detector_defs.h"
#include "sls/versionAPI.h"
@ -87,7 +88,7 @@ void Detector::loadParameters(const std::vector<std::string> &parameters) {
for (const auto &current_line : parameters) {
parser.Parse(current_line);
proxy.Call(parser.command(), parser.arguments(), parser.detector_id(),
defs::PUT_ACTION);
defs::PUT_ACTION, std::cout, parser.receiver_id());
}
}
@ -117,6 +118,10 @@ Result<int64_t> Detector::getDetectorServerVersion(Positions pos) const {
return pimpl->Parallel(&Module::getDetectorServerVersion, pos);
}
Result<std::string> Detector::getKernelVersion(Positions pos) const {
return pimpl->Parallel(&Module::getKernelVersion, pos);
}
Result<int64_t> Detector::getSerialNumber(Positions pos) const {
return pimpl->Parallel(&Module::getSerialNumber, pos);
}
@ -2129,6 +2134,7 @@ void Detector::setAdditionalJsonParameter(const std::string &key,
// Advanced
void Detector::programFPGA(const std::string &fname, Positions pos) {
LOG(logINFO) << "Updating Firmware...";
std::vector<char> buffer = pimpl->readProgrammingFile(fname);
pimpl->Parallel(&Module::programFPGA, pos, buffer);
rebootController(pos);
@ -2140,12 +2146,30 @@ void Detector::resetFPGA(Positions pos) {
void Detector::copyDetectorServer(const std::string &fname,
const std::string &hostname, Positions pos) {
LOG(logINFO) << "Updating Detector Server (via tftp)...";
pimpl->Parallel(&Module::copyDetectorServer, pos, fname, hostname);
if (getDetectorType().squash() != defs::EIGER) {
rebootController(pos);
}
}
void Detector::updateDetectorServer(const std::string &fname, Positions pos) {
LOG(logINFO) << "Updating Detector Server (no tftp)...";
std::vector<char> buffer = readBinaryFile(fname, "Update Detector Server");
std::string filename = sls::getFileNameFromFilePath(fname);
pimpl->Parallel(&Module::updateDetectorServer, pos, buffer, filename);
if (getDetectorType().squash() != defs::EIGER) {
rebootController(pos);
}
}
void Detector::updateKernel(const std::string &fname, Positions pos) {
LOG(logINFO) << "Updating Kernel...";
std::vector<char> buffer = sls::readBinaryFile(fname, "Update Kernel");
pimpl->Parallel(&Module::updateKernel, pos, buffer);
rebootController(pos);
}
void Detector::rebootController(Positions pos) {
pimpl->Parallel(&Module::rebootController, pos);
}
@ -2154,10 +2178,34 @@ void Detector::updateFirmwareAndServer(const std::string &sname,
const std::string &hostname,
const std::string &fname,
Positions pos) {
LOG(logINFO) << "Updating Firmware and Detector Server (with tftp)...";
LOG(logINFO) << "Updating Detector Server (via tftp)...";
pimpl->Parallel(&Module::copyDetectorServer, pos, sname, hostname);
programFPGA(fname, pos);
}
void Detector::updateFirmwareAndServer(const std::string &sname,
const std::string &fname,
Positions pos) {
LOG(logINFO) << "Updating Firmware and Detector Server (no tftp)...";
LOG(logINFO) << "Updating Detector Server (no tftp)...";
std::vector<char> buffer = readBinaryFile(sname, "Update Detector Server");
std::string filename = sls::getFileNameFromFilePath(sname);
pimpl->Parallel(&Module::updateDetectorServer, pos, buffer, filename);
programFPGA(fname, pos);
}
Result<bool> Detector::getUpdateMode(Positions pos) const {
return pimpl->Parallel(&Module::getUpdateMode, pos);
}
void Detector::setUpdateMode(const bool updatemode, Positions pos) {
pimpl->Parallel(&Module::setUpdateMode, pos, updatemode);
if (getDetectorType().squash() != defs::EIGER) {
rebootController(pos);
}
}
Result<uint32_t> Detector::readRegister(uint32_t addr, Positions pos) const {
return pimpl->Parallel(&Module::readRegister, pos, addr);
}
@ -2236,7 +2284,7 @@ Result<sls::IpAddr> Detector::getLastClientIP(Positions pos) const {
Result<std::string> Detector::executeCommand(const std::string &value,
Positions pos) {
return pimpl->Parallel(&Module::execCommand, pos, value);
return pimpl->Parallel(&Module::executeCommand, pos, value);
}
Result<int64_t> Detector::getNumberOfFramesFromStart(Positions pos) const {

View File

@ -12,6 +12,7 @@
#include "sls/ToString.h"
#include "sls/container_utils.h"
#include "sls/file_utils.h"
#include "sls/network_utils.h"
#include "sls/string_utils.h"
@ -337,7 +338,9 @@ void DetectorImpl::updateDetectorSize() {
<< shm()->numberOfChannels.y;
for (auto &module : modules) {
module->updateNumberOfModule(shm()->numberOfModule);
if (module->getUpdateMode() == 0) {
module->updateNumberOfModule(shm()->numberOfModule);
}
}
}
@ -1261,8 +1264,7 @@ std::vector<char> DetectorImpl::readProgrammingFile(const std::string &fname) {
throw RuntimeError("programfpga not implemented for this detector");
}
LOG(logINFO)
<< "Updating Firmware. This can take awhile. Please be patient...";
LOG(logINFO) << "This can take awhile. Please be patient.";
LOG(logDEBUG1) << "Programming FPGA with file name:" << fname;
// check if it exists
@ -1280,14 +1282,7 @@ std::vector<char> DetectorImpl::readProgrammingFile(const std::string &fname) {
}
// get srcSize to print progress
if (fseek(src, 0, SEEK_END) != 0) {
throw RuntimeError("Program FPGA: Seek error in src file");
}
size_t srcSize = ftell(src);
if (srcSize <= 0) {
throw RuntimeError("Program FPGA: Could not get length of source file");
}
rewind(src);
ssize_t srcSize = sls::getFileSize(src, "Program FPGA");
// create temp destination file
char destfname[] = "/tmp/SLS_DET_MCB.XXXXXX";
@ -1359,36 +1354,12 @@ std::vector<char> DetectorImpl::readProgrammingFile(const std::string &fname) {
if (close(dst) != 0) {
throw RuntimeError("Program FPGA: Could not close destination file");
}
LOG(logINFOBLUE) << "File has been converted to " << destfname;
LOG(logINFO) << "File has been converted to " << destfname;
// loading dst file to memory
// FILE *fp = fopen("/tmp/SLS_DET_MCB.tzgmUT", "r");
FILE *fp = fopen(destfname, "r");
if (fp == nullptr) {
throw RuntimeError("Program FPGA: Could not open rawbin file");
}
if (fseek(fp, 0, SEEK_END) != 0) {
throw RuntimeError("Program FPGA: Seek error in rawbin file");
}
size_t filesize = ftell(fp);
if (filesize <= 0) {
throw RuntimeError("Program FPGA: Could not get length of rawbin file");
}
rewind(fp);
std::vector<char> buffer(filesize, 0);
if (fread(buffer.data(), sizeof(char), filesize, fp) != filesize) {
throw RuntimeError("Program FPGA: Could not read rawbin file");
}
if (fclose(fp) != 0) {
throw RuntimeError(
"Program FPGA: Could not close destination file after converting");
}
// unlink(destfname); // delete temporary file
LOG(logDEBUG1) << "Successfully loaded the rawbin file to program memory";
LOG(logDEBUG1) << "Read file into memory";
// load converted file to memory
std::vector<char> buffer = readBinaryFile(destfname, "Program FPGA");
// delete temporary
unlink(destfname);
return buffer;
}

View File

@ -284,7 +284,7 @@ class DetectorImpl : public virtual slsDetectorDefs {
/**
* Convert raw file
* [Jungfrau][Ctb] from pof file
* [Jungfrau][Ctb][Moench] from pof file
* [Mythen3][Gotthard2] from rbf file
* @param fname name of pof/rbf file
* @returns binary of the program

View File

@ -94,6 +94,12 @@ int64_t Module::getDetectorServerVersion() const {
return sendToDetector<int64_t>(F_GET_SERVER_VERSION);
}
std::string Module::getKernelVersion() const {
char retval[MAX_STR_LENGTH]{};
sendToDetector(F_GET_KERNEL_VERSION, nullptr, retval);
return retval;
}
int64_t Module::getSerialNumber() const {
return sendToDetector<int64_t>(F_GET_SERIAL_NUMBER);
}
@ -830,8 +836,9 @@ std::vector<uint64_t> Module::getNumMissingPackets() const {
auto client = ReceiverSocket(shm()->rxHostname, shm()->rxTCPPort);
client.Send(F_GET_NUM_MISSING_PACKETS);
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Receiver " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw ReceiverError(
"Receiver " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
} else {
auto nports = client.Receive<int>();
std::vector<uint64_t> retval(nports);
@ -1163,17 +1170,18 @@ std::string Module::getReceiverHostname() const {
}
void Module::setReceiverHostname(const std::string &receiverIP) {
LOG(logDEBUG1) << "Setting up Receiver with " << receiverIP;
LOG(logDEBUG1) << "Setting up Receiver hostname with " << receiverIP;
if (getRunStatus() == RUNNING) {
throw RuntimeError("Cannot set receiver hostname. Acquisition already "
"running. Stop it first.");
}
if (receiverIP == "none") {
memset(shm()->rxHostname, 0, MAX_STR_LENGTH);
sls::strcpy_safe(shm()->rxHostname, "none");
shm()->useReceiverFlag = false;
}
if (getRunStatus() == RUNNING) {
LOG(logWARNING) << "Acquisition already running, Stopping it.";
stopAcquisition();
return;
}
// start updating
@ -1522,8 +1530,8 @@ void Module::sendReceiverRateCorrections(const std::vector<int64_t> &t) {
receiver.Send(static_cast<int>(t.size()));
receiver.Send(t);
if (receiver.Receive<int>() == FAIL) {
throw RuntimeError("Receiver " + std::to_string(moduleIndex) +
" returned error: " + receiver.readErrorMessage());
throw ReceiverError("Receiver " + std::to_string(moduleIndex) +
" returned error: " + receiver.readErrorMessage());
}
}
@ -1778,8 +1786,8 @@ void Module::sendVetoPhoton(const int chipIndex,
client.Send(gainIndices);
client.Send(values);
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw DetectorError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
}
}
@ -1790,15 +1798,15 @@ void Module::getVetoPhoton(const int chipIndex,
client.Send(F_GET_VETO_PHOTON);
client.Send(chipIndex);
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw DetectorError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
}
auto nch = client.Receive<int>();
if (nch != shm()->nChan.x) {
throw RuntimeError("Could not get veto photon. Expected " +
std::to_string(shm()->nChan.x) + " channels, got " +
std::to_string(nch));
throw DetectorError("Could not get veto photon. Expected " +
std::to_string(shm()->nChan.x) + " channels, got " +
std::to_string(nch));
}
std::vector<int> gainIndices(nch);
std::vector<int> values(nch);
@ -2025,8 +2033,8 @@ void Module::getBadChannels(const std::string &fname) const {
auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.Send(F_GET_BAD_CHANNELS);
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw DetectorError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
}
// receive badchannels
auto nch = client.Receive<int>();
@ -2082,8 +2090,8 @@ void Module::setBadChannels(const std::string &fname) {
client.Send(badchannels);
}
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw DetectorError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
}
}
@ -2396,8 +2404,8 @@ std::map<std::string, std::string> Module::getAdditionalJsonHeader() const {
auto client = ReceiverSocket(shm()->rxHostname, shm()->rxTCPPort);
client.Send(F_GET_ADDITIONAL_JSON_HEADER);
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Receiver " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw ReceiverError("Receiver " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
} else {
auto size = client.Receive<int>();
std::string buff(size, '\0');
@ -2445,8 +2453,8 @@ void Module::setAdditionalJsonHeader(
client.Send(&buff[0], buff.size());
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Receiver " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw ReceiverError("Receiver " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
}
}
@ -2479,14 +2487,15 @@ void Module::programFPGA(std::vector<char> buffer) {
case JUNGFRAU:
case CHIPTESTBOARD:
case MOENCH:
programFPGAviaBlackfin(buffer);
sendProgram(true, buffer, F_PROGRAM_FPGA, "Update Firmware");
break;
case MYTHEN3:
case GOTTHARD2:
programFPGAviaNios(buffer);
sendProgram(false, buffer, F_PROGRAM_FPGA, "Update Firmware");
break;
default:
throw RuntimeError("Program FPGA is not implemented for this detector");
throw RuntimeError("Updating Firmware via the package is not "
"implemented for this detector");
}
}
@ -2497,7 +2506,8 @@ void Module::copyDetectorServer(const std::string &fname,
char args[2][MAX_STR_LENGTH]{};
sls::strcpy_safe(args[0], fname.c_str());
sls::strcpy_safe(args[1], hostname.c_str());
LOG(logINFO) << "Sending detector server " << args[0] << " from host "
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): Sending detector server " << args[0] << " from host "
<< args[1];
auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.Send(F_COPY_DET_SERVER);
@ -2507,15 +2517,65 @@ void Module::copyDetectorServer(const std::string &fname,
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw RuntimeError(os.str());
throw DetectorError(os.str());
}
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): detector server copied";
<< "): Detector server copied";
}
void Module::updateDetectorServer(std::vector<char> buffer,
const std::string &serverName) {
switch (shm()->detType) {
case JUNGFRAU:
case CHIPTESTBOARD:
case MOENCH:
sendProgram(true, buffer, F_UPDATE_DETECTOR_SERVER,
"Update Detector Server (no tftp)", serverName);
break;
case MYTHEN3:
case GOTTHARD2:
case EIGER:
sendProgram(false, buffer, F_UPDATE_DETECTOR_SERVER,
"Update Detector Server (no tftp)", serverName);
break;
default:
throw RuntimeError(
"Updating DetectorServer via the package is not implemented "
"for this detector");
}
}
void Module::updateKernel(std::vector<char> buffer) {
switch (shm()->detType) {
case JUNGFRAU:
case CHIPTESTBOARD:
case MOENCH:
sendProgram(true, buffer, F_UPDATE_KERNEL, "Update Kernel");
break;
case MYTHEN3:
case GOTTHARD2:
sendProgram(false, buffer, F_UPDATE_KERNEL, "Update Kernel");
break;
default:
throw RuntimeError("Updating Kernel via the package is not implemented "
"for this detector");
}
}
void Module::rebootController() {
sendToDetector(F_REBOOT_CONTROLLER);
LOG(logINFO) << "Controller rebooted successfully!";
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): Controller rebooted successfully!";
}
bool Module::getUpdateMode() const {
return sendToDetector<int>(F_GET_UPDATE_MODE);
}
void Module::setUpdateMode(const bool updatemode) {
sendToDetector(F_SET_UPDATE_MODE, static_cast<int>(updatemode), nullptr);
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): Update Mode set to " << updatemode << "!";
}
uint32_t Module::readRegister(uint32_t addr) const {
@ -2593,11 +2653,25 @@ sls::IpAddr Module::getLastClientIP() const {
return sendToDetector<sls::IpAddr>(F_GET_LAST_CLIENT_IP);
}
std::string Module::execCommand(const std::string &cmd) {
std::string Module::executeCommand(const std::string &cmd) {
char arg[MAX_STR_LENGTH]{};
char retval[MAX_STR_LENGTH]{};
sls::strcpy_safe(arg, cmd.c_str());
sendToDetector(F_EXEC_COMMAND, arg, retval);
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): Sending command " << cmd;
auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.Send(F_EXEC_COMMAND);
client.Send(arg);
if (client.Receive<int>() == FAIL) {
std::cout << '\n';
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw DetectorError(os.str());
}
client.Receive(retval);
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): command executed";
return retval;
}
@ -3154,8 +3228,8 @@ void Module::setModule(sls_detector_module &module, bool trimbits) {
client.Send(F_SET_MODULE);
sendModule(&module, client);
if (client.Receive<int>() == FAIL) {
throw RuntimeError("Detector " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
throw DetectorError("Module " + std::to_string(moduleIndex) +
" returned error: " + client.readErrorMessage());
}
}
@ -3401,193 +3475,128 @@ sls_detector_module Module::readSettingsFile(const std::string &fname,
return myMod;
}
void Module::programFPGAviaBlackfin(std::vector<char> buffer) {
// send program from memory to detector
LOG(logINFO) << "Sending programming binary (from pof) to module "
<< moduleIndex << " (" << shm()->hostname << ")";
void Module::sendProgram(bool blackfin, std::vector<char> buffer,
const int functionEnum,
const std::string &functionType,
const std::string serverName) {
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): Sending " << functionType;
// send fnum and filesize
auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.Send(F_PROGRAM_FPGA);
client.Send(functionEnum);
uint64_t filesize = buffer.size();
client.Send(filesize);
// checksum
// send checksum
std::string checksum = sls::md5_calculate_checksum(buffer.data(), filesize);
LOG(logDEBUG1) << "Checksum:" << checksum;
char cChecksum[MAX_STR_LENGTH];
memset(cChecksum, 0, MAX_STR_LENGTH);
char cChecksum[MAX_STR_LENGTH] = {0};
strcpy(cChecksum, checksum.c_str());
client.Send(cChecksum);
// opening file fail
if (client.Receive<int>() == FAIL) {
std::cout << '\n';
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw RuntimeError(os.str());
// send server name
if (functionEnum == F_UPDATE_DETECTOR_SERVER) {
char sname[MAX_STR_LENGTH] = {0};
strcpy(sname, serverName.c_str());
client.Send(sname);
}
// sending program in parts of 2mb each
uint64_t unitprogramsize = 0;
int currentPointer = 0;
while (filesize > 0) {
unitprogramsize = MAX_FPGAPROGRAMSIZE; // 2mb
if (unitprogramsize > filesize) { // less than 2mb
unitprogramsize = filesize;
}
LOG(logDEBUG) << "unitprogramsize:" << unitprogramsize
<< "\t filesize:" << filesize;
client.Send(&buffer[currentPointer], unitprogramsize);
if (client.Receive<int>() == FAIL) {
std::cout << '\n';
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw RuntimeError(os.str());
}
filesize -= unitprogramsize;
currentPointer += unitprogramsize;
}
// checksum
// validate memory allocation etc in detector
if (client.Receive<int>() == FAIL) {
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw RuntimeError(os.str());
throw DetectorError(os.str());
}
// send program
if (blackfin) {
uint64_t unitprogramsize = 0;
int currentPointer = 0;
while (filesize > 0) {
unitprogramsize = MAX_BLACKFIN_PROGRAM_SIZE;
if (unitprogramsize > filesize) {
unitprogramsize = filesize;
}
LOG(logDEBUG) << "unitprogramsize:" << unitprogramsize
<< "\t filesize:" << filesize;
client.Send(&buffer[currentPointer], unitprogramsize);
if (client.Receive<int>() == FAIL) {
std::cout << '\n';
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw DetectorError(os.str());
}
filesize -= unitprogramsize;
currentPointer += unitprogramsize;
}
} else {
client.Send(buffer);
}
// tmp checksum verified in detector
if (client.Receive<int>() == FAIL) {
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw DetectorError(os.str());
}
LOG(logINFO) << "Checksum verified for module " << moduleIndex << " ("
<< shm()->hostname << ")";
// simulating erasing flash
{
LOG(logINFO) << "(Simulating) Erasing Flash for module " << moduleIndex
<< " (" << shm()->hostname << ")";
printf("%d%%\r", 0);
std::cout << std::flush;
// erasing takes 65 seconds, printing here (otherwise need threads
// in server-unnecessary)
const int ERASE_TIME = 65;
int count = ERASE_TIME + 1;
while (count > 0) {
std::this_thread::sleep_for(std::chrono::seconds(1));
--count;
printf("%d%%\r",
static_cast<int>(
(static_cast<double>(ERASE_TIME - count) / ERASE_TIME) *
100));
std::cout << std::flush;
// simulating erasing and writing to
if (blackfin) {
if (functionEnum == F_PROGRAM_FPGA) {
simulatingActivityinDetector("Erasing Flash",
BLACKFIN_ERASE_FLASH_TIME);
simulatingActivityinDetector("Writing to Flash",
BLACKFIN_WRITE_TO_FLASH_TIME);
}
} else {
if (functionEnum == F_PROGRAM_FPGA) {
simulatingActivityinDetector("Erasing Flash",
NIOS_ERASE_FLASH_TIME_FPGA);
simulatingActivityinDetector("Writing to Flash",
NIOS_WRITE_TO_FLASH_TIME_FPGA);
} else if (functionEnum == F_UPDATE_KERNEL) {
simulatingActivityinDetector("Erasing Flash",
NIOS_ERASE_FLASH_TIME_KERNEL);
simulatingActivityinDetector("Writing to Flash",
NIOS_WRITE_TO_FLASH_TIME_KERNEL);
}
printf("\n");
}
// simulating writing to flash
{
LOG(logINFO) << "(Simulating) Writing to Flash for module "
<< moduleIndex << " (" << shm()->hostname << ")";
printf("%d%%\r", 0);
std::cout << std::flush;
// writing takes 30 seconds, printing here (otherwise need threads
// in server-unnecessary)
const int ERASE_TIME = 30;
int count = ERASE_TIME + 1;
while (count > 0) {
std::this_thread::sleep_for(std::chrono::seconds(1));
--count;
printf("%d%%\r",
static_cast<int>(
(static_cast<double>(ERASE_TIME - count) / ERASE_TIME) *
100));
std::cout << std::flush;
}
printf("\n");
}
// update verified
if (client.Receive<int>() == FAIL) {
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw RuntimeError(os.str());
throw DetectorError(os.str());
}
LOG(logINFO) << "FPGA programmed successfully";
LOG(logINFO) << "Module " << moduleIndex << " (" << shm()->hostname
<< "): " << functionType << " successful";
}
void Module::programFPGAviaNios(std::vector<char> buffer) {
LOG(logINFO) << "Sending programming binary (from rbf) to Module "
void Module::simulatingActivityinDetector(const std::string &functionType,
const int timeRequired) {
LOG(logINFO) << "(Simulating) " << functionType << " for module "
<< moduleIndex << " (" << shm()->hostname << ")";
auto client = DetectorSocket(shm()->hostname, shm()->controlPort);
client.Send(F_PROGRAM_FPGA);
uint64_t filesize = buffer.size();
client.Send(filesize);
// checksum
std::string checksum = sls::md5_calculate_checksum(buffer.data(), filesize);
LOG(logDEBUG1) << "Checksum:" << checksum;
char cChecksum[MAX_STR_LENGTH];
memset(cChecksum, 0, MAX_STR_LENGTH);
strcpy(cChecksum, checksum.c_str());
client.Send(cChecksum);
// validate file size before sending program
if (client.Receive<int>() == FAIL) {
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw RuntimeError(os.str());
}
client.Send(buffer);
// simulating erasing flash
{
LOG(logINFO) << "(Simulating) Erasing Flash for module " << moduleIndex
<< " (" << shm()->hostname << ")";
printf("%d%%\r", 0);
printf("%d%%\r", 0);
std::cout << std::flush;
const int ERASE_TIME = timeRequired;
int count = ERASE_TIME + 1;
while (count > 0) {
std::this_thread::sleep_for(std::chrono::seconds(1));
--count;
printf(
"%d%%\r",
static_cast<int>(
(static_cast<double>(ERASE_TIME - count) / ERASE_TIME) * 100));
std::cout << std::flush;
// erasing takes 10 seconds, printing here (otherwise need threads
// in server-unnecessary)
const int ERASE_TIME = 10;
int count = ERASE_TIME + 1;
while (count > 0) {
std::this_thread::sleep_for(std::chrono::seconds(1));
--count;
printf("%d%%\r",
static_cast<int>(
(static_cast<double>(ERASE_TIME - count) / ERASE_TIME) *
100));
std::cout << std::flush;
}
printf("\n");
}
// simulating writing to flash
{
LOG(logINFO) << "(Simulating) Writing to Flash for module "
<< moduleIndex << " (" << shm()->hostname << ")";
printf("%d%%\r", 0);
std::cout << std::flush;
// writing takes 45 seconds, printing here (otherwise need threads
// in server-unnecessary)
const int ERASE_TIME = 45;
int count = ERASE_TIME + 1;
while (count > 0) {
std::this_thread::sleep_for(std::chrono::seconds(1));
--count;
printf("%d%%\r",
static_cast<int>(
(static_cast<double>(ERASE_TIME - count) / ERASE_TIME) *
100));
std::cout << std::flush;
}
printf("\n");
}
if (client.Receive<int>() == FAIL) {
std::ostringstream os;
os << "Module " << moduleIndex << " (" << shm()->hostname << ")"
<< " returned error: " << client.readErrorMessage();
throw RuntimeError(os.str());
}
LOG(logINFO) << "FPGA programmed successfully";
printf("\n");
}
} // namespace sls

View File

@ -91,6 +91,7 @@ class Module : public virtual slsDetectorDefs {
int64_t getFirmwareVersion() const;
int64_t getDetectorServerVersion() const;
std::string getKernelVersion() const;
int64_t getSerialNumber() const;
int getModuleId() const;
int64_t getReceiverSoftwareVersion() const;
@ -540,7 +541,12 @@ class Module : public virtual slsDetectorDefs {
void resetFPGA();
void copyDetectorServer(const std::string &fname,
const std::string &hostname);
void updateDetectorServer(std::vector<char> buffer,
const std::string &serverName);
void updateKernel(std::vector<char> buffer);
void rebootController();
bool getUpdateMode() const;
void setUpdateMode(const bool updatemode);
uint32_t readRegister(uint32_t addr) const;
uint32_t writeRegister(uint32_t addr, uint32_t val);
void setBit(uint32_t addr, int n);
@ -564,7 +570,7 @@ class Module : public virtual slsDetectorDefs {
bool getLockDetector() const;
void setLockDetector(bool lock);
sls::IpAddr getLastClientIP() const;
std::string execCommand(const std::string &cmd);
std::string executeCommand(const std::string &cmd);
int64_t getNumberOfFramesFromStart() const;
int64_t getActualTime() const;
int64_t getMeasurementTime() const;
@ -745,11 +751,20 @@ class Module : public virtual slsDetectorDefs {
std::string getTrimbitFilename(detectorSettings settings, int e_eV);
sls_detector_module readSettingsFile(const std::string &fname,
bool trimbits = true);
void programFPGAviaBlackfin(std::vector<char> buffer);
void programFPGAviaNios(std::vector<char> buffer);
void sendProgram(bool blackfin, std::vector<char> buffer,
const int functionEnum, const std::string &functionType,
const std::string serverName = "");
void simulatingActivityinDetector(const std::string &functionType,
const int timeRequired);
const int moduleIndex;
mutable sls::SharedMemory<sharedModule> shm{0, 0};
static const int BLACKFIN_ERASE_FLASH_TIME = 65;
static const int BLACKFIN_WRITE_TO_FLASH_TIME = 30;
static const int NIOS_ERASE_FLASH_TIME_FPGA = 10;
static const int NIOS_WRITE_TO_FLASH_TIME_FPGA = 45;
static const int NIOS_ERASE_FLASH_TIME_KERNEL = 9;
static const int NIOS_WRITE_TO_FLASH_TIME_KERNEL = 40;
};
} // namespace sls

View File

@ -103,6 +103,13 @@ TEST_CASE("detectorserverversion", "[.cmd]") {
REQUIRE_THROWS(proxy.Call("detectorserverversion", {"0"}, -1, PUT));
}
TEST_CASE("kernelversion", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
REQUIRE_NOTHROW(proxy.Call("kernelversion", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("kernelversion", {"0"}, -1, PUT));
}
TEST_CASE("serialnumber", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
@ -533,7 +540,13 @@ TEST_CASE("fliprows", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER || det_type == defs::JUNGFRAU) {
bool jungfrauhw2 = false;
if (det_type == defs::JUNGFRAU &&
((det.getSerialNumber().tsquash("inconsistent serial number to test") &
0x30000) == 0x30000)) {
jungfrauhw2 = true;
}
if (det_type == defs::EIGER || jungfrauhw2) {
auto previous = det.getFlipRows();
auto previous_numudp = det.getNumberofUDPInterfaces();
if (det_type == defs::JUNGFRAU) {
@ -1544,32 +1557,47 @@ TEST_CASE("readnrows", "[.cmd]") {
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::EIGER || det_type == defs::JUNGFRAU) {
auto prev_val = det.getReadNRows();
{
std::ostringstream oss;
proxy.Call("readnrows", {"256"}, -1, PUT, oss);
REQUIRE(oss.str() == "readnrows 256\n");
bool jungfrauhw2 = false;
if (det_type == defs::JUNGFRAU &&
((det.getSerialNumber().tsquash(
"inconsistent serial number to test") &
0x30000) == 0x30000)) {
jungfrauhw2 = true;
}
{
std::ostringstream oss;
proxy.Call("readnrows", {}, -1, GET, oss);
REQUIRE(oss.str() == "readnrows 256\n");
}
{
std::ostringstream oss;
proxy.Call("readnrows", {"16"}, -1, PUT, oss);
REQUIRE(oss.str() == "readnrows 16\n");
}
if (det_type == defs::JUNGFRAU) {
REQUIRE_THROWS(proxy.Call("readnrows", {"7"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"20"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"44"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"513"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"1"}, -1, PUT));
}
REQUIRE_THROWS(proxy.Call("readnrows", {"0"}, -1, PUT));
for (int i = 0; i != det.size(); ++i) {
det.setReadNRows(prev_val[i], {i});
if (det_type == defs::JUNGFRAU && !jungfrauhw2) {
{
std::ostringstream oss;
proxy.Call("readnrows", {}, -1, GET, oss);
REQUIRE(oss.str() == "readnrows 512\n");
}
} else {
auto prev_val = det.getReadNRows();
{
std::ostringstream oss;
proxy.Call("readnrows", {"256"}, -1, PUT, oss);
REQUIRE(oss.str() == "readnrows 256\n");
}
{
std::ostringstream oss;
proxy.Call("readnrows", {}, -1, GET, oss);
REQUIRE(oss.str() == "readnrows 256\n");
}
{
std::ostringstream oss;
proxy.Call("readnrows", {"16"}, -1, PUT, oss);
REQUIRE(oss.str() == "readnrows 16\n");
}
if (det_type == defs::JUNGFRAU) {
REQUIRE_THROWS(proxy.Call("readnrows", {"7"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"20"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"44"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"513"}, -1, PUT));
REQUIRE_THROWS(proxy.Call("readnrows", {"1"}, -1, PUT));
}
REQUIRE_THROWS(proxy.Call("readnrows", {"0"}, -1, PUT));
for (int i = 0; i != det.size(); ++i) {
det.setReadNRows(prev_val[i], {i});
}
}
} else {
REQUIRE_THROWS(proxy.Call("readnrows", {}, -1, GET));
@ -1998,8 +2026,6 @@ TEST_CASE("stop", "[.cmd]") {
REQUIRE_THROWS(proxy.Call("stop", {}, -1, GET));
auto det_type = det.getDetectorType().squash();
std::chrono::nanoseconds prev_val;
bool virtualDet =
det.isVirtualDetectorServer().tsquash("inconsistent virtual servers");
if (det_type != defs::MYTHEN3) {
prev_val = det.getExptime().tsquash("inconsistent exptime to test");
} else {
@ -2030,11 +2056,8 @@ TEST_CASE("stop", "[.cmd]") {
{
std::ostringstream oss;
proxy.Call("status", {}, -1, GET, oss);
if (!virtualDet && det_type == defs::JUNGFRAU) {
REQUIRE(oss.str() == "status stopped\n");
} else {
REQUIRE(oss.str() == "status idle\n");
}
REQUIRE(((oss.str() == "status stopped\n") ||
(oss.str() == "status idle\n")));
}
det.setExptime(-1, prev_val);
det.setPeriod(prev_period);
@ -2046,8 +2069,6 @@ TEST_CASE("status", "[.cmd]") {
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
std::chrono::nanoseconds prev_val;
bool virtualDet =
det.isVirtualDetectorServer().tsquash("inconsistent virtual servers");
if (det_type != defs::MYTHEN3) {
prev_val = det.getExptime().tsquash("inconsistent exptime to test");
} else {
@ -2074,11 +2095,8 @@ TEST_CASE("status", "[.cmd]") {
{
std::ostringstream oss;
proxy.Call("status", {}, -1, GET, oss);
if (!virtualDet && det_type == defs::JUNGFRAU) {
REQUIRE(oss.str() == "status stopped\n");
} else {
REQUIRE(oss.str() == "status idle\n");
}
REQUIRE(((oss.str() == "status stopped\n") ||
(oss.str() == "status idle\n")));
}
det.setExptime(-1, prev_val);
det.setPeriod(prev_period);
@ -2701,6 +2719,25 @@ TEST_CASE("copydetectorserver", "[.cmd]") {
}
}
TEST_CASE("updatekernel", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);
auto det_type = det.getDetectorType().squash();
if (det_type == defs::JUNGFRAU || det_type == defs::CHIPTESTBOARD ||
det_type == defs::MOENCH || det_type == defs::MYTHEN3 ||
det_type == defs::GOTTHARD2) {
// TODO: send real server?
// std::ostringstream oss;
// proxy.Call("updatekernel",{"juImage_detector.lzma",
// "pc13784"}, -1, PUT, oss);
// REQUIRE(oss.str() == "updatekernel successful\n");
REQUIRE_THROWS(proxy.Call("updatekernel", {}, -1, GET));
} else {
REQUIRE_THROWS(proxy.Call("updatekernel", {}, -1, GET));
REQUIRE_THROWS(proxy.Call("updatekernel", {}, -1, PUT));
}
}
TEST_CASE("rebootcontroller", "[.cmd]") {
Detector det;
CmdProxy proxy(&det);

View File

@ -104,7 +104,7 @@ if (SLS_USE_RECEIVER_BINARIES)
set_target_properties(slsReceiver PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
if(SLS_LTO_AVAILABLE)
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET slsReceiver PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()
@ -124,7 +124,7 @@ if (SLS_USE_RECEIVER_BINARIES)
set_target_properties(slsMultiReceiver PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
)
if(SLS_LTO_AVAILABLE)
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET slsMultiReceiver PROPERTY INTERPROCEDURAL_OPTIMIZATION True)
endif()

View File

@ -355,7 +355,7 @@ std::string Implementation::getFilePath() const { return filePath; }
void Implementation::setFilePath(const std::string &c) {
if (!c.empty()) {
mkdir_p(c); // throws if it can't create
sls::mkdir_p(c); // throws if it can't create
filePath = c;
}
LOG(logINFO) << "File path: " << filePath;

View File

@ -66,21 +66,21 @@ target_include_directories(md5sls
# Create an object library to avoid building the library twice
add_library(slsSupportStatic STATIC
add_library(slsSupportObject OBJECT
${SOURCES}
${HEADERS}
)
target_include_directories(slsSupportStatic
target_include_directories(slsSupportObject
PUBLIC
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
)
target_link_libraries(slsSupportStatic
target_link_libraries(slsSupportObject
PUBLIC
slsProjectOptions
# libzmq
libzmq
rapidjson
PRIVATE
slsProjectWarnings
@ -92,33 +92,33 @@ if (SLS_USE_TESTS)
endif(SLS_USE_TESTS)
#List of targets to support adding removing targets as config
set(SUPPORT_LIBRARY_TARGETS slsSupportStatic)
set(SUPPORT_LIBRARY_TARGETS slsSupportObject)
# Add shared library version of the support lib
# if(SLS_BUILD_SHARED_LIBRARIES)
# add_library(slsSupportShared SHARED $<TARGET_OBJECTS:slsSupportObject>)
# target_link_libraries(slsSupportShared PUBLIC slsSupportObject)
if(SLS_BUILD_SHARED_LIBRARIES)
add_library(slsSupportShared SHARED $<TARGET_OBJECTS:slsSupportObject>)
target_link_libraries(slsSupportShared PUBLIC slsSupportObject)
# set_target_properties(slsSupportShared PROPERTIES
# VERSION ${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}.${PACKAGE_VERSION_PATCH}
# SOVERSION ${PACKAGE_VERSION_MAJOR}
# LIBRARY_OUTPUT_NAME SlsSupport
# LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
# PUBLIC_HEADER "${PUBLICHEADERS}"
# )
# list(APPEND SUPPORT_LIBRARY_TARGETS slsSupportShared)
# endif(SLS_BUILD_SHARED_LIBRARIES)
set_target_properties(slsSupportShared PROPERTIES
VERSION ${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}.${PACKAGE_VERSION_PATCH}
SOVERSION ${PACKAGE_VERSION_MAJOR}
LIBRARY_OUTPUT_NAME SlsSupport
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
PUBLIC_HEADER "${PUBLICHEADERS}"
)
list(APPEND SUPPORT_LIBRARY_TARGETS slsSupportShared)
endif(SLS_BUILD_SHARED_LIBRARIES)
# Add static version of the support lib
# add_library(slsSupportStatic STATIC $<TARGET_OBJECTS:slsSupportObject>)
# target_link_libraries(slsSupportStatic PUBLIC slsSupportObject)
add_library(slsSupportStatic STATIC $<TARGET_OBJECTS:slsSupportObject>)
target_link_libraries(slsSupportStatic PUBLIC slsSupportObject)
set_target_properties(slsSupportStatic PROPERTIES
ARCHIVE_OUTPUT_NAME SlsSupportStatic
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
PUBLIC_HEADER "${PUBLICHEADERS}"
)
# list(APPEND SUPPORT_LIBRARY_TARGETS slsSupportStatic)
list(APPEND SUPPORT_LIBRARY_TARGETS slsSupportStatic)
if((CMAKE_BUILD_TYPE STREQUAL "Release") AND SLS_LTO_AVAILABLE)
set_property(TARGET ${SUPPORT_LIBRARY_TARGETS} PROPERTY INTERPROCEDURAL_OPTIMIZATION True)

View File

@ -8,49 +8,46 @@
#include <fstream>
#include <string>
/** (used by multi and sls)
* reads a short int raw data file
* @param infile input file stream
namespace sls {
/**
* @param data array of data values
* @param nch number of channels
* @param offset start channel value
* @returns OK or FAIL if it could not read the file or data=NULL
*/
int readDataFile(std::ifstream &infile, short int *data, int nch,
int offset = 0);
/** (used by multi and sls)
* reads a short int rawdata file
* @param fname name of the file to be read
/**
* @param data array of data value
* @param nch number of channels
* @returns OK or FAIL if it could not read the file or data=NULL
*/
int readDataFile(std::string fname, short int *data, int nch);
/** (used by multi and sls)
* writes a short int raw data file
* @param outfile output file stream
std::vector<char> readBinaryFile(const std::string &fname,
const std::string &errorPrefix);
/**
* @param nch number of channels
* @param data array of data values
* @param offset start channel number
* @returns OK or FAIL if it could not write the file or data=NULL
*/
int writeDataFile(std::ofstream &outfile, int nch, short int *data,
int offset = 0);
/** (used by multi and sls)
* writes a short int raw data file
* @param fname of the file to be written
/**
* @param nch number of channels
* @param data array of data values
* @returns OK or FAIL if it could not write the file or data=NULL
*/
int writeDataFile(std::string fname, int nch, short int *data);
// mkdir -p path implemented by recursive calls
void mkdir_p(const std::string &path, std::string dir = "");
namespace sls {
int getFileSize(std::ifstream &ifs);
ssize_t getFileSize(FILE* fd, const std::string &prependErrorString);
std::string getFileNameFromFilePath(const std::string &fpath);
}

View File

@ -55,9 +55,8 @@
/** maximum trim en */
#define MAX_TRIMEN 100
/** maximum unit size of program sent to detector */
//#define MAX_FPGAPROGRAMSIZE (2 * 1024 * 1024)
#define MAX_FPGAPROGRAMSIZE (128 * 1024)
/** maximum unit size of program sent to blackfin */
#define MAX_BLACKFIN_PROGRAM_SIZE (128 * 1024)
#define GET_FLAG -1

View File

@ -253,6 +253,11 @@ enum detFuncs {
F_SET_UDP_FIRST_DEST,
F_GET_READOUT_SPEED,
F_SET_READOUT_SPEED,
F_GET_KERNEL_VERSION,
F_UPDATE_KERNEL,
F_UPDATE_DETECTOR_SERVER,
F_GET_UPDATE_MODE,
F_SET_UPDATE_MODE,
NUM_DET_FUNCTIONS,
RECEIVER_ENUM_START = 256, /**< detector function should not exceed this
@ -608,9 +613,15 @@ const char* getFunctionNameFromEnum(enum detFuncs func) {
case F_SET_UDP_FIRST_DEST: return "F_SET_UDP_FIRST_DEST";
case F_GET_READOUT_SPEED: return "F_GET_READOUT_SPEED";
case F_SET_READOUT_SPEED: return "F_SET_READOUT_SPEED";
case F_GET_KERNEL_VERSION: return "F_GET_KERNEL_VERSION";
case F_UPDATE_DETECTOR_SERVER: return "F_UPDATE_DETECTOR_SERVER";
case F_GET_UPDATE_MODE: return "F_GET_UPDATE_MODE";
case F_SET_UPDATE_MODE: return "F_SET_UPDATE_MODE";
case NUM_DET_FUNCTIONS: return "NUM_DET_FUNCTIONS";
case RECEIVER_ENUM_START: return "RECEIVER_ENUM_START";
case F_EXEC_RECEIVER_COMMAND: return "F_EXEC_RECEIVER_COMMAND";
case F_LOCK_RECEIVER: return "F_LOCK_RECEIVER";
case F_GET_LAST_RECEIVER_CLIENT_IP: return "F_GET_LAST_RECEIVER_CLIENT_IP";

View File

@ -1,15 +1,15 @@
// SPDX-License-Identifier: LGPL-3.0-or-other
// Copyright (C) 2021 Contributors to the SLS Detector Package
/** API versions */
#define GITBRANCH "6.0.0"
#define GITBRANCH "6.1.1"
#define APILIB 0x211021
#define APIRECEIVER 0x211020
#define APIGUI 0x211021
#define APICTB 0x211021
#define APIGOTTHARD 0x211021
#define APIGOTTHARD2 0x211021
#define APIJUNGFRAU 0x211021
#define APIMYTHEN3 0x211021
#define APIMOENCH 0x211021
#define APIEIGER 0x211021
#define APILIB 0x211125
#define APIRECEIVER 0x211125
#define APIGUI 0x211125
#define APICTB 0x211125
#define APIGOTTHARD 0x211125
#define APIGOTTHARD2 0x211125
#define APIMYTHEN3 0x211125
#define APIMOENCH 0x211124
#define APIEIGER 0x211125
#define APIJUNGFRAU 0x220104

View File

@ -10,249 +10,249 @@
#include <string.h>
#include <thread>
#include <vector>
// #include <zmq.h>
#include <zmq.h>
using namespace rapidjson;
ZmqSocket::ZmqSocket(const char *const hostname_or_ip,
const uint32_t portnumber)
: portno(portnumber), sockfd(false) {
// Extra check that throws if conversion fails, could be removed
// auto ipstr = sls::HostnameToIp(hostname_or_ip).str();
// std::ostringstream oss;
// oss << "tcp://" << ipstr << ":" << portno;
// sockfd.serverAddress = oss.str();
// LOG(logDEBUG) << "zmq address: " << sockfd.serverAddress;
auto ipstr = sls::HostnameToIp(hostname_or_ip).str();
std::ostringstream oss;
oss << "tcp://" << ipstr << ":" << portno;
sockfd.serverAddress = oss.str();
LOG(logDEBUG) << "zmq address: " << sockfd.serverAddress;
// // create context
// sockfd.contextDescriptor = zmq_ctx_new();
// if (sockfd.contextDescriptor == nullptr)
// throw sls::ZmqSocketError("Could not create contextDescriptor");
// create context
sockfd.contextDescriptor = zmq_ctx_new();
if (sockfd.contextDescriptor == nullptr)
throw sls::ZmqSocketError("Could not create contextDescriptor");
// // create subscriber
// sockfd.socketDescriptor = zmq_socket(sockfd.contextDescriptor, ZMQ_SUB);
// if (sockfd.socketDescriptor == nullptr) {
// PrintError();
// throw sls::ZmqSocketError("Could not create socket");
// }
// create subscriber
sockfd.socketDescriptor = zmq_socket(sockfd.contextDescriptor, ZMQ_SUB);
if (sockfd.socketDescriptor == nullptr) {
PrintError();
throw sls::ZmqSocketError("Could not create socket");
}
// // Socket Options provided above
// // an empty string implies receiving any messages
// if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_SUBSCRIBE, "", 0)) {
// PrintError();
// throw sls::ZmqSocketError("Could set socket opt");
// }
// // ZMQ_LINGER default is already -1 means no messages discarded. use this
// // options if optimizing required ZMQ_SNDHWM default is 0 means no limit.
// // use this to optimize if optimizing required eg. int value = -1;
// const int value = 0;
// if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_LINGER, &value,
// sizeof(value))) {
// PrintError();
// throw sls::ZmqSocketError("Could not set ZMQ_LINGER");
// }
// LOG(logDEBUG) << "Default receive high water mark:"
// << GetReceiveHighWaterMark();
// Socket Options provided above
// an empty string implies receiving any messages
if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_SUBSCRIBE, "", 0)) {
PrintError();
throw sls::ZmqSocketError("Could set socket opt");
}
// ZMQ_LINGER default is already -1 means no messages discarded. use this
// options if optimizing required ZMQ_SNDHWM default is 0 means no limit.
// use this to optimize if optimizing required eg. int value = -1;
const int value = 0;
if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_LINGER, &value,
sizeof(value))) {
PrintError();
throw sls::ZmqSocketError("Could not set ZMQ_LINGER");
}
LOG(logDEBUG) << "Default receive high water mark:"
<< GetReceiveHighWaterMark();
}
ZmqSocket::ZmqSocket(const uint32_t portnumber, const char *ethip)
: portno(portnumber), sockfd(true) {
// create context
// sockfd.contextDescriptor = zmq_ctx_new();
// if (sockfd.contextDescriptor == nullptr)
// throw sls::ZmqSocketError("Could not create contextDescriptor");
sockfd.contextDescriptor = zmq_ctx_new();
if (sockfd.contextDescriptor == nullptr)
throw sls::ZmqSocketError("Could not create contextDescriptor");
// // create publisher
// sockfd.socketDescriptor = zmq_socket(sockfd.contextDescriptor, ZMQ_PUB);
// if (sockfd.socketDescriptor == nullptr) {
// PrintError();
// throw sls::ZmqSocketError("Could not create socket");
// }
// LOG(logDEBUG) << "Default send high water mark:" << GetSendHighWaterMark();
// create publisher
sockfd.socketDescriptor = zmq_socket(sockfd.contextDescriptor, ZMQ_PUB);
if (sockfd.socketDescriptor == nullptr) {
PrintError();
throw sls::ZmqSocketError("Could not create socket");
}
LOG(logDEBUG) << "Default send high water mark:" << GetSendHighWaterMark();
// // construct address, can be refactored with libfmt
// std::ostringstream oss;
// oss << "tcp://" << ethip << ":" << portno;
// sockfd.serverAddress = oss.str();
// LOG(logDEBUG) << "zmq address: " << sockfd.serverAddress;
// construct address, can be refactored with libfmt
std::ostringstream oss;
oss << "tcp://" << ethip << ":" << portno;
sockfd.serverAddress = oss.str();
LOG(logDEBUG) << "zmq address: " << sockfd.serverAddress;
// // bind address
// if (zmq_bind(sockfd.socketDescriptor, sockfd.serverAddress.c_str())) {
// PrintError();
// throw sls::ZmqSocketError("Could not bind socket");
// }
// // sleep to allow a slow-joiner
// std::this_thread::sleep_for(std::chrono::milliseconds(200));
// bind address
if (zmq_bind(sockfd.socketDescriptor, sockfd.serverAddress.c_str())) {
PrintError();
throw sls::ZmqSocketError("Could not bind socket");
}
// sleep to allow a slow-joiner
std::this_thread::sleep_for(std::chrono::milliseconds(200));
};
int ZmqSocket::GetSendHighWaterMark() {
int value = 0;
// size_t value_size = sizeof(value);
// if (zmq_getsockopt(sockfd.socketDescriptor, ZMQ_SNDHWM, &value,
// &value_size)) {
// PrintError();
// throw sls::ZmqSocketError("Could not get ZMQ_SNDHWM");
// }
size_t value_size = sizeof(value);
if (zmq_getsockopt(sockfd.socketDescriptor, ZMQ_SNDHWM, &value,
&value_size)) {
PrintError();
throw sls::ZmqSocketError("Could not get ZMQ_SNDHWM");
}
return value;
}
void ZmqSocket::SetSendHighWaterMark(int limit) {
// if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_SNDHWM, &limit,
// sizeof(limit))) {
// PrintError();
// throw sls::ZmqSocketError("Could not set ZMQ_SNDHWM");
// }
if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_SNDHWM, &limit,
sizeof(limit))) {
PrintError();
throw sls::ZmqSocketError("Could not set ZMQ_SNDHWM");
}
}
int ZmqSocket::GetReceiveHighWaterMark() {
int value = 0;
// size_t value_size = sizeof(value);
// if (zmq_getsockopt(sockfd.socketDescriptor, ZMQ_RCVHWM, &value,
// &value_size)) {
// PrintError();
// throw sls::ZmqSocketError("Could not get ZMQ_SNDHWM");
// }
size_t value_size = sizeof(value);
if (zmq_getsockopt(sockfd.socketDescriptor, ZMQ_RCVHWM, &value,
&value_size)) {
PrintError();
throw sls::ZmqSocketError("Could not get ZMQ_SNDHWM");
}
return value;
}
void ZmqSocket::SetReceiveHighWaterMark(int limit) {
// if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_RCVHWM, &limit,
// sizeof(limit))) {
// PrintError();
// throw sls::ZmqSocketError("Could not set ZMQ_SNDHWM");
// }
if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_RCVHWM, &limit,
sizeof(limit))) {
PrintError();
throw sls::ZmqSocketError("Could not set ZMQ_SNDHWM");
}
}
int ZmqSocket::Connect() {
// if (zmq_connect(sockfd.socketDescriptor, sockfd.serverAddress.c_str())) {
// PrintError();
// return 1;
// }
if (zmq_connect(sockfd.socketDescriptor, sockfd.serverAddress.c_str())) {
PrintError();
return 1;
}
return 0;
}
int ZmqSocket::SendHeader(int index, zmqHeader header) {
// /** Json Header Format */
// const char jsonHeaderFormat[] = "{"
// "\"jsonversion\":%u, "
// "\"bitmode\":%u, "
// "\"fileIndex\":%lu, "
// "\"detshape\":[%u, %u], "
// "\"shape\":[%u, %u], "
// "\"size\":%u, "
// "\"acqIndex\":%lu, "
// "\"frameIndex\":%lu, "
// "\"progress\":%lf, "
// "\"fname\":\"%s\", "
// "\"data\": %d, "
// "\"completeImage\": %d, "
/** Json Header Format */
const char jsonHeaderFormat[] = "{"
"\"jsonversion\":%u, "
"\"bitmode\":%u, "
"\"fileIndex\":%lu, "
"\"detshape\":[%u, %u], "
"\"shape\":[%u, %u], "
"\"size\":%u, "
"\"acqIndex\":%lu, "
"\"frameIndex\":%lu, "
"\"progress\":%lf, "
"\"fname\":\"%s\", "
"\"data\": %d, "
"\"completeImage\": %d, "
// "\"frameNumber\":%lu, "
// "\"expLength\":%u, "
// "\"packetNumber\":%u, "
// "\"bunchId\":%lu, "
// "\"timestamp\":%lu, "
// "\"modId\":%u, "
// "\"row\":%u, "
// "\"column\":%u, "
// "\"reserved\":%u, "
// "\"debug\":%u, "
// "\"roundRNumber\":%u, "
// "\"detType\":%u, "
// "\"version\":%u, "
"\"frameNumber\":%lu, "
"\"expLength\":%u, "
"\"packetNumber\":%u, "
"\"bunchId\":%lu, "
"\"timestamp\":%lu, "
"\"modId\":%u, "
"\"row\":%u, "
"\"column\":%u, "
"\"reserved\":%u, "
"\"debug\":%u, "
"\"roundRNumber\":%u, "
"\"detType\":%u, "
"\"version\":%u, "
// // additional stuff
// "\"flipRows\":%u, "
// "\"quad\":%u"
// additional stuff
"\"flipRows\":%u, "
"\"quad\":%u"
// ; //"}\n";
// memset(header_buffer.get(), '\0', MAX_STR_LENGTH); // TODO! Do we need this
// sprintf(header_buffer.get(), jsonHeaderFormat, header.jsonversion,
// header.dynamicRange, header.fileIndex, header.ndetx, header.ndety,
// header.npixelsx, header.npixelsy, header.imageSize, header.acqIndex,
// header.frameIndex, header.progress, header.fname.c_str(),
// header.data ? 1 : 0, header.completeImage ? 1 : 0,
; //"}\n";
memset(header_buffer.get(), '\0', MAX_STR_LENGTH); // TODO! Do we need this
sprintf(header_buffer.get(), jsonHeaderFormat, header.jsonversion,
header.dynamicRange, header.fileIndex, header.ndetx, header.ndety,
header.npixelsx, header.npixelsy, header.imageSize, header.acqIndex,
header.frameIndex, header.progress, header.fname.c_str(),
header.data ? 1 : 0, header.completeImage ? 1 : 0,
// header.frameNumber, header.expLength, header.packetNumber,
// header.bunchId, header.timestamp, header.modId, header.row,
// header.column, header.reserved, header.debug, header.roundRNumber,
// header.detType, header.version,
header.frameNumber, header.expLength, header.packetNumber,
header.bunchId, header.timestamp, header.modId, header.row,
header.column, header.reserved, header.debug, header.roundRNumber,
header.detType, header.version,
// // additional stuff
// header.flipRows, header.quad);
// additional stuff
header.flipRows, header.quad);
// if (!header.addJsonHeader.empty()) {
// strcat(header_buffer.get(), ", ");
// strcat(header_buffer.get(), "\"addJsonHeader\": {");
// for (auto it = header.addJsonHeader.begin();
// it != header.addJsonHeader.end(); ++it) {
// if (it != header.addJsonHeader.begin()) {
// strcat(header_buffer.get(), ", ");
// }
// strcat(header_buffer.get(), "\"");
// strcat(header_buffer.get(), it->first.c_str());
// strcat(header_buffer.get(), "\":\"");
// strcat(header_buffer.get(), it->second.c_str());
// strcat(header_buffer.get(), "\"");
// }
// strcat(header_buffer.get(), " } ");
// }
if (!header.addJsonHeader.empty()) {
strcat(header_buffer.get(), ", ");
strcat(header_buffer.get(), "\"addJsonHeader\": {");
for (auto it = header.addJsonHeader.begin();
it != header.addJsonHeader.end(); ++it) {
if (it != header.addJsonHeader.begin()) {
strcat(header_buffer.get(), ", ");
}
strcat(header_buffer.get(), "\"");
strcat(header_buffer.get(), it->first.c_str());
strcat(header_buffer.get(), "\":\"");
strcat(header_buffer.get(), it->second.c_str());
strcat(header_buffer.get(), "\"");
}
strcat(header_buffer.get(), " } ");
}
// strcat(header_buffer.get(), "}\n");
// int length = strlen(header_buffer.get());
strcat(header_buffer.get(), "}\n");
int length = strlen(header_buffer.get());
// #ifdef VERBOSE
// // if(!index)
// cprintf(BLUE, "%d : Streamer: buf: %s\n", index, buf);
// #endif
#ifdef VERBOSE
// if(!index)
cprintf(BLUE, "%d : Streamer: buf: %s\n", index, buf);
#endif
// if (zmq_send(sockfd.socketDescriptor, header_buffer.get(), length,
// header.data ? ZMQ_SNDMORE : 0) < 0) {
// PrintError();
// return 0;
// }
// #ifdef VERBOSE
// cprintf(GREEN, "[%u] send header data\n", portno);
// #endif
if (zmq_send(sockfd.socketDescriptor, header_buffer.get(), length,
header.data ? ZMQ_SNDMORE : 0) < 0) {
PrintError();
return 0;
}
#ifdef VERBOSE
cprintf(GREEN, "[%u] send header data\n", portno);
#endif
return 1;
}
int ZmqSocket::SendData(char *buf, int length) {
// if (zmq_send(sockfd.socketDescriptor, buf, length, 0) < 0) {
// PrintError();
// return 0;
// }
if (zmq_send(sockfd.socketDescriptor, buf, length, 0) < 0) {
PrintError();
return 0;
}
return 1;
}
int ZmqSocket::ReceiveHeader(const int index, zmqHeader &zHeader,
uint32_t version) {
// const int bytes_received = zmq_recv(sockfd.socketDescriptor,
// header_buffer.get(), MAX_STR_LENGTH, 0);
// if (bytes_received > 0) {
// #ifdef ZMQ_DETAIL
// cprintf(BLUE, "Header %d [%d] Length: %d Header:%s \n", index, portno,
// bytes_received, buffer.data());
// #endif
// if (ParseHeader(index, bytes_received, header_buffer.get(), zHeader,
// version)) {
// #ifdef ZMQ_DETAIL
// cprintf(RED, "Parsed Header %d [%d] Length: %d Header:%s \n", index,
// portno, bytes_received, buffer.data());
// #endif
// if (!zHeader.data) {
// #ifdef ZMQ_DETAIL
// cprintf(RED, "%d [%d] Received end of acquisition\n", index,
// portno);
// #endif
// return 0;
// }
// #ifdef ZMQ_DETAIL
// cprintf(GREEN, "%d [%d] data\n", index, portno);
// #endif
// return 1;
// }
// }
const int bytes_received = zmq_recv(sockfd.socketDescriptor,
header_buffer.get(), MAX_STR_LENGTH, 0);
if (bytes_received > 0) {
#ifdef ZMQ_DETAIL
cprintf(BLUE, "Header %d [%d] Length: %d Header:%s \n", index, portno,
bytes_received, buffer.data());
#endif
if (ParseHeader(index, bytes_received, header_buffer.get(), zHeader,
version)) {
#ifdef ZMQ_DETAIL
cprintf(RED, "Parsed Header %d [%d] Length: %d Header:%s \n", index,
portno, bytes_received, buffer.data());
#endif
if (!zHeader.data) {
#ifdef ZMQ_DETAIL
cprintf(RED, "%d [%d] Received end of acquisition\n", index,
portno);
#endif
return 0;
}
#ifdef ZMQ_DETAIL
cprintf(GREEN, "%d [%d] data\n", index, portno);
#endif
return 1;
}
}
return 0;
};
@ -323,96 +323,96 @@ int ZmqSocket::ParseHeader(const int index, int length, char *buff,
}
int ZmqSocket::ReceiveData(const int index, char *buf, const int size) {
// zmq_msg_t message;
// zmq_msg_init(&message);
// int length = ReceiveMessage(index, message);
// if (length == size) {
// memcpy(buf, (char *)zmq_msg_data(&message), size);
// } else if (length < size) {
// memcpy(buf, (char *)zmq_msg_data(&message), length);
// memset(buf + length, 0xFF, size - length);
// } else {
// LOG(logERROR) << "Received weird packet size " << length
// << " for socket " << index;
// memset(buf, 0xFF, size);
// }
zmq_msg_t message;
zmq_msg_init(&message);
int length = ReceiveMessage(index, message);
if (length == size) {
memcpy(buf, (char *)zmq_msg_data(&message), size);
} else if (length < size) {
memcpy(buf, (char *)zmq_msg_data(&message), length);
memset(buf + length, 0xFF, size - length);
} else {
LOG(logERROR) << "Received weird packet size " << length
<< " for socket " << index;
memset(buf, 0xFF, size);
}
// zmq_msg_close(&message);
return 1;
zmq_msg_close(&message);
return length;
}
int ZmqSocket::ReceiveMessage(const int index, zmq_msg_t &message) {
// int length = zmq_msg_recv(&message, sockfd.socketDescriptor, 0);
// if (length == -1) {
// PrintError();
// LOG(logERROR) << "Could not read header for socket " << index;
// }
return 1;
int length = zmq_msg_recv(&message, sockfd.socketDescriptor, 0);
if (length == -1) {
PrintError();
LOG(logERROR) << "Could not read header for socket " << index;
}
return length;
}
void ZmqSocket::PrintError() {
// switch (errno) {
// case EINVAL:
// LOG(logERROR) << "The socket type/option or value/endpoint supplied is "
// "invalid (zmq)";
// break;
// case EAGAIN:
// LOG(logERROR) << "Non-blocking mode was requested and the message "
// "cannot be sent/available at the moment (zmq)";
// break;
// case ENOTSUP:
// LOG(logERROR) << "The zmq_send()/zmq_msg_recv() operation is not "
// "supported by this socket type (zmq)";
// break;
// case EFSM:
// LOG(logERROR) << "The zmq_send()/zmq_msg_recv() unavailable now as "
// "socket in inappropriate state (eg. ZMQ_REP). Look up "
// "messaging patterns (zmq)";
// break;
// case EFAULT:
// LOG(logERROR) << "The provided context/message is invalid (zmq)";
// break;
// case EMFILE:
// LOG(logERROR) << "The limit on the total number of open ØMQ sockets "
// "has been reached (zmq)";
// break;
// case EPROTONOSUPPORT:
// LOG(logERROR)
// << "The requested transport protocol is not supported (zmq)";
// break;
// case ENOCOMPATPROTO:
// LOG(logERROR) << "The requested transport protocol is not compatible "
// "with the socket type (zmq)";
// break;
// case EADDRINUSE:
// LOG(logERROR) << "The requested address is already in use (zmq)";
// break;
// case EADDRNOTAVAIL:
// LOG(logERROR) << "The requested address was not local (zmq)";
// break;
// case ENODEV:
// LOG(logERROR)
// << "The requested address specifies a nonexistent interface (zmq)";
// break;
// case ETERM:
// LOG(logERROR) << "The ØMQ context associated with the specified socket "
// "was terminated (zmq)";
// break;
// case ENOTSOCK:
// LOG(logERROR) << "The provided socket was invalid (zmq)";
// break;
// case EINTR:
// LOG(logERROR)
// << "The operation was interrupted by delivery of a signal (zmq)";
// break;
// case EMTHREAD:
// LOG(logERROR)
// << "No I/O thread is available to accomplish the task (zmq)";
// break;
// default:
// LOG(logERROR) << "Unknown socket error (zmq)";
// break;
// }
switch (errno) {
case EINVAL:
LOG(logERROR) << "The socket type/option or value/endpoint supplied is "
"invalid (zmq)";
break;
case EAGAIN:
LOG(logERROR) << "Non-blocking mode was requested and the message "
"cannot be sent/available at the moment (zmq)";
break;
case ENOTSUP:
LOG(logERROR) << "The zmq_send()/zmq_msg_recv() operation is not "
"supported by this socket type (zmq)";
break;
case EFSM:
LOG(logERROR) << "The zmq_send()/zmq_msg_recv() unavailable now as "
"socket in inappropriate state (eg. ZMQ_REP). Look up "
"messaging patterns (zmq)";
break;
case EFAULT:
LOG(logERROR) << "The provided context/message is invalid (zmq)";
break;
case EMFILE:
LOG(logERROR) << "The limit on the total number of open ØMQ sockets "
"has been reached (zmq)";
break;
case EPROTONOSUPPORT:
LOG(logERROR)
<< "The requested transport protocol is not supported (zmq)";
break;
case ENOCOMPATPROTO:
LOG(logERROR) << "The requested transport protocol is not compatible "
"with the socket type (zmq)";
break;
case EADDRINUSE:
LOG(logERROR) << "The requested address is already in use (zmq)";
break;
case EADDRNOTAVAIL:
LOG(logERROR) << "The requested address was not local (zmq)";
break;
case ENODEV:
LOG(logERROR)
<< "The requested address specifies a nonexistent interface (zmq)";
break;
case ETERM:
LOG(logERROR) << "The ØMQ context associated with the specified socket "
"was terminated (zmq)";
break;
case ENOTSOCK:
LOG(logERROR) << "The provided socket was invalid (zmq)";
break;
case EINTR:
LOG(logERROR)
<< "The operation was interrupted by delivery of a signal (zmq)";
break;
case EMTHREAD:
LOG(logERROR)
<< "No I/O thread is available to accomplish the task (zmq)";
break;
default:
LOG(logERROR) << "Unknown socket error (zmq)";
break;
}
}
// Nested class to do RAII handling of socket descriptors
@ -423,19 +423,19 @@ ZmqSocket::mySocketDescriptors::~mySocketDescriptors() {
Close();
}
void ZmqSocket::mySocketDescriptors::Disconnect() {
// if (server)
// zmq_unbind(socketDescriptor, serverAddress.c_str());
// else
// zmq_disconnect(socketDescriptor, serverAddress.c_str());
if (server)
zmq_unbind(socketDescriptor, serverAddress.c_str());
else
zmq_disconnect(socketDescriptor, serverAddress.c_str());
};
void ZmqSocket::mySocketDescriptors::Close() {
// if (socketDescriptor != nullptr) {
// zmq_close(socketDescriptor);
// socketDescriptor = nullptr;
// }
if (socketDescriptor != nullptr) {
zmq_close(socketDescriptor);
socketDescriptor = nullptr;
}
// if (contextDescriptor != nullptr) {
// zmq_ctx_destroy(contextDescriptor);
// contextDescriptor = nullptr;
// }
if (contextDescriptor != nullptr) {
zmq_ctx_destroy(contextDescriptor);
contextDescriptor = nullptr;
}
};

View File

@ -11,6 +11,8 @@
#include <sys/stat.h>
#include <sys/types.h>
namespace sls {
int readDataFile(std::ifstream &infile, short int *data, int nch, int offset) {
int ichan, iline = 0;
short int idata;
@ -53,6 +55,39 @@ int readDataFile(std::string fname, short int *data, int nch) {
return iline;
}
std::vector<char> readBinaryFile(const std::string &fname,
const std::string &errorPrefix) {
// check if it exists
struct stat st;
if (stat(fname.c_str(), &st) != 0) {
throw sls::RuntimeError(errorPrefix +
std::string(" (file does not exist)"));
}
FILE *fp = fopen(fname.c_str(), "rb");
if (fp == nullptr) {
throw sls::RuntimeError(errorPrefix +
std::string(" (Could not open file: ") + fname + std::string(")"));
}
// get file size to print progress
ssize_t filesize = sls::getFileSize(fp, errorPrefix);
std::vector<char> buffer(filesize, 0);
if ((ssize_t)fread(buffer.data(), sizeof(char), filesize, fp) != filesize) {
throw sls::RuntimeError(errorPrefix +
std::string(" (Could not read file)"));
}
if (fclose(fp) != 0) {
throw sls::RuntimeError(errorPrefix +
std::string(" (Could not close file)"));
}
LOG(logDEBUG1) << "Read file into memory";
return buffer;
}
int writeDataFile(std::ofstream &outfile, int nch, short int *data,
int offset) {
if (data == nullptr)
@ -96,7 +131,6 @@ void mkdir_p(const std::string &path, std::string dir) {
mkdir_p(path.substr(i + 1), dir);
}
namespace sls {
int getFileSize(std::ifstream &ifs) {
auto current_pos = ifs.tellg();
ifs.seekg(0, std::ios::end);
@ -104,4 +138,27 @@ int getFileSize(std::ifstream &ifs) {
ifs.seekg(current_pos);
return file_size;
}
std::string getFileNameFromFilePath(const std::string &fpath) {
std::string fname(fpath);
std::size_t slashPos = fpath.rfind('/');
if (slashPos != std::string::npos) {
fname = fpath.substr(slashPos + 1, fpath.size() - 1);
}
return fname;
}
ssize_t getFileSize(FILE* fd, const std::string &prependErrorString) {
if (fseek(fd, 0, SEEK_END) != 0) {
throw RuntimeError(prependErrorString + std::string(" (Seek error in src file)"));
}
size_t fileSize = ftell(fd);
if (fileSize <= 0) {
throw RuntimeError(prependErrorString + std::string(" (Could not get length of source file)"));
}
rewind(fd);
return fileSize;
}
} // namespace sls

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