merge conflict sorted, removing rest

This commit is contained in:
Dhanya Maliakal 2017-12-05 11:25:10 +01:00
commit 0ef52138e1
17 changed files with 34 additions and 967 deletions

View File

@ -1,6 +1,5 @@
cmake_minimum_required(VERSION 2.8)
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
set (REST OFF)
set (CALIBRATE OFF)
option (USE_HDF5 "HDF5 File format" OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")

View File

@ -221,7 +221,6 @@ help:
@echo ""
@echo ""
@echo "Makefile variables"
@echo "REST=yes compile REST-aware Receiver (POCO and JsonBox libraries required)"
@echo "DEBUG=1,2 set debug level to 1 (VERBOSE) or 2 (VERYVERBOSE)"
@echo ""
@echo ""

View File

@ -33,26 +33,6 @@ ifeq ($(HDF5),yes)
endif
##############################################################
# EigerSLS specific. Set this to yes, if you want to compile
# EigerSLS code: in this case, you need also POCO and JsonBox
# libraries
##############################################################
REST = no
POCODIR = /afs/psi.ch/user/s/sala/public/poco
JSONBOXDIR = /opt/JsonBox-0.5
RESTFLAGS = -L$(POCODIR)/lib -Wl,-rpath=$(POCODIR)/lib -L$(JSONBOXDIR) -Wl,-rpath=$(JSONBOXDIR) -lPocoNet -lPocoFoundation -lJsonBox
ifeq ($(REST),yes)
LDFLAGRXR = -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsReceiver $(RESTFLAGS) -DREST
INCLUDESRXR = $(EIGERFLAGS) -I$(POCODIR)/include -I$(JSONBOXDIR)/include
endif
##############################################################
# ROOTSLS specific. Set this to yes, if you want to compile
# ROOTSLS code: in this case, you need also root libraries

View File

@ -1,8 +0,0 @@
#!/bin/bash
git $@
for i in sls*/; do
cd $i
echo $i
git $@
cd ..
done

View File

@ -143,7 +143,6 @@ INPUT = commonFiles/communication_funcs.h \
../slsReceiverSoftware/include/logger.h \
../slsReceiverSoftware/include/MySocketTCP.h \
../slsReceiverSoftware/include/receiver_defs.h \
../slsReceiverSoftware/include/RestHelper.h \
../slsReceiverSoftware/include/sls_receiver_defs.h \
../slsReceiverSoftware/include/sls_receiver_funcs.h \
../slsReceiverSoftware/include/slsReceiver.h \
@ -152,7 +151,6 @@ INPUT = commonFiles/communication_funcs.h \
../slsReceiverSoftware/include/ThreadObject.h \
../slsReceiverSoftware/include/UDPBaseImplementation.h \
../slsReceiverSoftware/include/UDPInterface.h \
../slsReceiverSoftware/include/UDPRESTImplementation.h \
../slsReceiverSoftware/include/UDPStandardImplementation.h \
../slsReceiverSoftware/include/utilities.h \
../slsReceiverSoftware/include/ZmqSocket.h

View File

@ -17,16 +17,6 @@ set(SOURCES
)
# REST
if (REST)
MESSAGE("\n *** Using REST Implementation *** \n")
list (APPEND SOURCES src/UDPRestImplementation.cpp)
# add_library(poco etc.)
else (REST)
MESSAGE("\n *** Using Standard Implementation *** \n")
endif (REST)
# HDF5
if (USE_HDF5)
if (HDF5_FOUND)

View File

@ -33,10 +33,6 @@ ifeq ($(HDF5),yes)
SRC_CLNT += HDF5File.cpp HDF5FileStatic.cpp
endif
ifeq ($(REST), yes)
SRC_CLNT += UDPRESTImplementation.cpp
endif
MAIN_SRC = main.cpp
@ -48,15 +44,6 @@ $(info # In slsReceiverSoftware Makefile #)
$(info #######################################)
$(info )
ifeq ($(REST), yes)
$(info )
$(info !#####################################!)
$(info ! PLEASE ENSURE THAT VARIABLES !)
$(info ! POCODIR and JSONBOXDIR !)
$(info ! ARE PROPERLY SETUP!!! !)
$(info !#####################################!)
$(info )
endif
.PHONY: all intdoc package eigerReceiver clean

View File

@ -1,308 +0,0 @@
#pragma once
/**
* @file RestHelper.h
* @author Leonardo Sala <leonardo.sala@psi.ch>
* @date Tue Mar 25 09:28:19 2014
*
* @brief
*
*
*/
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h>
#include <Poco/Timespan.h>
#include "JsonBox/Value.h"
#include "JsonBox/JsonParsingError.h"
//#include "logger.h"
#include <iostream>
#include <sstream>
#include <string>
#include <exception>
#include <unistd.h>
using namespace Poco::Net;
using namespace Poco;
using namespace std;
class RestHelper {
public:
RestHelper(int timeout=10, int n_tries=1){
/**
*
*
* @param timeout default=10
* @param n_tries default=1
*/
http_timeout = timeout;
n_connection_tries = n_tries;
}
~RestHelper(){
delete session;
};
void set_connection_params(int timeout, int n_tries){
http_timeout = timeout;
n_connection_tries = n_tries;
}
void get_connection_params(int *timeout, int *n_tries){
*timeout = http_timeout;
*n_tries = n_connection_tries;
}
void init(string hostname, int port){
/** Initialize the RestHelper. Hostname and port parameters are not supposed to change.
*
*
* @param hostname FQDN of the host to connect to , e.g. www.iamfake.org, or sodoi.org
* @param port
*
* @return
*/
//Check for http:// string
string proto_str = "http://";
if( size_t found = hostname.find(proto_str) != string::npos ){
char c1[hostname.size()-found-1];
size_t length1 = hostname.copy(c1, hostname.size()-found-1, proto_str.size());
c1[length1]='\0';
hostname = c1;
}
full_hostname = "http://"+hostname;
session = new HTTPClientSession(hostname, port );
session->setKeepAliveTimeout( Timespan( http_timeout,0) );
};
void init(string hostname_port){
/** Initialize the RestHelper. Hostname_port parameters are not supposed to change.
*
*
* @param hostname FQDN and port of the host to connect to , e.g. www.iamfake.org:8080, or sodoi.org:1111. Default port is 8080
*
* @return
*/
//Check for http:// string
string proto_str = "http://";
if( size_t found = hostname_port.find(proto_str) != string::npos ){
char c1[hostname_port.size()-found-1];
size_t length1 = hostname_port.copy(c1, hostname_port.size()-found-1, proto_str.size());
c1[length1]='\0';
hostname_port = c1;
}
size_t found = hostname_port.rfind(":");
char c1[ found ], c2[hostname_port.size()-found-1];
string hostname;
size_t length1 = hostname_port.copy(c1, found);
c1[length1]='\0';
hostname = c1;
size_t length2 = hostname_port.copy(c2, found-1, found+1);
c2[length2]='\0';
int port = atoi(c2);
full_hostname = proto_str+hostname;
session = new HTTPClientSession(hostname,port );
session->setKeepAliveTimeout( Timespan( http_timeout,0) );
};
int get_json(string request, string* answer){
/** Retrieves a reply from the RESTful webservice.
*
*
* @param request Request without the hostname, e.g. if the full request would have been http://fake.org/fakemethod, request=fakemethod
* @param answer
*
* @return 0 if successful, -1 if failure happens.
*/
URI * uri = new URI(full_hostname+"/"+request);
string path(uri->getPathAndQuery());
if (path.empty()) path = "/";
// send request
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json\r\n");
int code = send_request(session, req, answer);
delete uri;
return code;
};
int get_json(string request, JsonBox::Value* json_value){
/**
*
*
* @param request
* @param json_value
*
* @return
*/
URI *uri = new URI(full_hostname+"/"+request);
string path(uri->getPathAndQuery());
if (path.empty()) path = "/";
// send request
HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json\r\n");
string answer;
int code = send_request(session, req, &answer);
if(code == 0 ) {
FILE_LOG(logDEBUG) << __AT__ << " REQUEST: " << " ANSWER: " << answer;
json_value->loadFromString(answer);
}
delete uri;
return code;
};
int post_json(string request, string *answer, string request_body="{}"){
/**
*
*
* @param request
* @param answer
* @param request_body Eventual arguments to the URL, e.g. action=login&name=mammamia
*
* @return
*/
//from: http://stackoverflow.com/questions/1499086/poco-c-net-ssl-how-to-post-https-request
URI *uri = new URI(full_hostname+"/"+request);
string path(uri->getPathAndQuery());
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1 );
req.setContentType("application/json\r\n");
req.setContentLength( request_body.length() );
int code = send_request(session, req, answer, request_body);
delete uri;
return code;
}
int post_json(string request, JsonBox::Value* json_value, string request_body="{}"){
/**
*
*
* @param request
* @param json_value
* @param request_body Eventual arguments to the URL, e.g. action=login&name=mammamia
*
* @return
*/
URI *uri = new URI(full_hostname+"/"+request);
string path(uri->getPathAndQuery());
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1 );
//this does not work
//req.setContentType("application/json\r\n");
//req.setContentLength( request.length() );
string answer;
int code = send_request(session, req, &answer, request_body);
if(code==0){
try{
json_value->loadFromString(answer);
}
catch (JsonBox::JsonParsingError& e){
try{
json_value->loadFromString("{\"global_state\":\"" + answer + "\"}");
}
catch(exception &e){
FILE_LOG(logERROR) << "Exception converting answer: " << e.what() ;
}
}
}
delete uri;
return code;
}
private:
HTTPClientSession *session;
string full_hostname;
/// HTTP timeout in seconds, default is 8
int http_timeout;
/// Number of connection tries
int n_connection_tries;
int send_request(HTTPClientSession *session, HTTPRequest &req, string *answer, string request_body=""){
/**
*
*
* @param session
* @param req
* @param answer
* @param request_body
*
* @return
*/
int n = 0;
int code = -1;
while(n < n_connection_tries){
req.setContentType("application/json");
//without this you need to tell the lenght: http://pocoproject.org/forum/viewtopic.php?f=12&t=5741&p=10019&hilit=post+json#p10019
// request.setContentLength(my_string.length());
req.setChunkedTransferEncoding(true);
try {
//istringstream rs(request_body);
//req.read(rs);
//cout << " --- " << rs << endl;
if (request_body == "")
session->sendRequest( (req) );
else{
ostream &os = session->sendRequest( req ) ;
os << request_body;
}
HTTPResponse res;
istream &is = session->receiveResponse(res);
StreamCopier::copyToString(is, *answer);
code = res.getStatus();
if (code != 200){
FILE_LOG(logERROR) << "HTTP ERROR " << res.getStatus() << ": " << res.getReason() ;
code = -1;
}
else
code = 0;
return code;
}
catch (exception& e){
FILE_LOG(logERROR) << "Exception connecting to "<< full_hostname << ": "<< e.what() << ", sleeping 5 seconds (" << n << "/"<<n_connection_tries << ")";
sleep(5);
}
n+=1;
}
std::cout << "Hostname: " << full_hostname << std::endl;
FILE_LOG(logERROR) << "Cannot connect to the REST server host " << full_hostname << "! Please check..." ;
throw std::runtime_error("Cannot connect to the REST server! Please check...");
//return code;
}
};

View File

@ -491,9 +491,9 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter
void setDetectorPositionId(const int i);
/**
* Sets detector hostname (and corresponding detector variables in derived REST class)
* Sets detector hostname
* It is second function called by the client when connecting to receiver.
* you can call this function only once. //FIXME: is this still valid, this implemented in derived REST class?
* you can call this function only once.
* @param c detector hostname
*/
void initialize(const char *c);

View File

@ -56,7 +56,7 @@ class UDPInterface {
*
* supported sequence of method-calls:
*
* initialize() : once and only once after create() //FIXME: only once functionality implemented in the derived REST class, so not mention here?
* initialize() : once and only once after create()
*
* get*() : anytime after initialize(), multiples times
*
@ -108,8 +108,8 @@ class UDPInterface {
/**
* Constructor
* Only non virtual function implemented in this class
* Factory create method to create a standard or REST object
* @param [in] receiver_type type can be standard or REST
* Factory create method to create a standard or custom object
* @param [in] receiver_type type can be standard or custom (must be derived from base class)
* @return a UDPInterface reference to object depending on receiver type
*/
static UDPInterface *create(string receiver_type = "standard");
@ -579,9 +579,9 @@ class UDPInterface {
virtual void setDetectorPositionId(const int i) = 0;
/**
* Sets detector hostname (and corresponding detector variables in derived REST class)
* Sets detector hostname
* It is second function called by the client when connecting to receiver.
* you can call this function only once. //FIXME: is this still valid, this implemented in derived REST class?
* you can call this function only once.
* @param c detector hostname
*/
virtual void initialize(const char *c) = 0;

View File

@ -1,135 +0,0 @@
//#ifdef REST
#pragma once
/********************************************//**
* @file UDPRESTImplementation.h
* @short does all the functions for a receiver, set/get parameters, start/stop etc.
***********************************************/
#include "UDPBaseImplementation.h"
#include "RestHelper.h"
#include "logger.h"
#include <string.h>
#include <stdio.h>
/**
* @short does all the functions for a receiver, set/get parameters, start/stop etc.
*/
class UDPRESTImplementation : protected virtual slsReceiverDefs, public UDPBaseImplementation {
public:
/*************************************************************************
* Constructor & Destructor **********************************************
*************************************************************************/
/**
* Constructor
*/
UDPRESTImplementation();
/**
* Destructor
*/
virtual ~UDPRESTImplementation();
protected:
/*************************************************************************
* Getters ***************************************************************
* They access local cache of configuration or detector parameters *******
*************************************************************************/
/**
* Get Rest State
*/
string get_rest_state(RestHelper * rest/*, string *rest_state*/);
/*************************************************************************
* Setters ***************************************************************
* They modify the local cache of configuration or detector parameters ***
*************************************************************************/
/**
* Initialize REST
*/
void initialize_REST();
public:
/*************************************************************************
* Getters ***************************************************************
* They access local cache of configuration or detector parameters *******
*************************************************************************/
/*************************************************************************
* Setters ***************************************************************
* They modify the local cache of configuration or detector parameters ***
*************************************************************************/
/**
* Overridden method
* Configure command line parameters
* @param config_map mapping of config parameters passed from command line arguments
*/
void configure(map<string, string> config_map);
/*************************************************************************
* Behavioral functions***************************************************
* They may modify the status of the receiver ****************************
*************************************************************************/
/**
* Overridden method
* Start Listening for Packets by activating all configuration settings to receiver
* When this function returns, it has status RUNNING(upon SUCCESS) or IDLE (upon failure)
* @param c error message if FAIL
* @return OK or FAIL
*/
int startReceiver(char *c=NULL);
/**
* Overridden method
* Stop Listening for Packets
* Calls startReadout(), which stops listening and sets status to Transmitting
* When it has read every frame in buffer, the status changes to Run_Finished
* When this function returns, receiver has status IDLE
* Pre: status is running, semaphores have been instantiated,
* Post: udp sockets shut down, status is idle, semaphores destroyed
*/
void stopReceiver();
/**
* Overridden method
* Stop Listening to Packets
* and sets status to Transmitting
* Next step would be to get all data and stop receiver completely and return with idle state
* Pre: status is running, udp sockets have been initialized, stop receiver initiated
* Post:udp sockets closed, status is transmitting,
*/
void startReadout();
/**
* Overridden method
* Shuts down and deletes UDP Sockets
* TCPIPInterface can also call this in case of illegal shutdown of receiver
*/
void shutDownUDPSockets();
uint64_t getTotalFramesCaught() const;
private:
bool isInitialized;
RestHelper * rest ;
int rest_port; // receiver backend port
string rest_hostname; // receiver hostname
bool is_main_receiver;
};
//#endif /*REST*/

View File

@ -78,17 +78,11 @@ public:
class FILELOG_DECLSPEC FILELog : public Log<Output2FILE> {};
//typedef Log<Output2FILE> FILELog;
#ifdef REST
#define FILE_LOG(level) \
if (level > FILELOG_MAX_LEVEL) ; \
else if (level > FILELog::ReportingLevel() || !Output2FILE::Stream()) ; \
else FILELog().Get(level)
#else
#define FILE_LOG(level) \
if (level > FILELOG_MAX_LEVEL) ; \
else if (level > FILELog::ReportingLevel() || !Output2FILE::Stream()) ; \
else FILELog().Get(level)
#endif
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
@ -151,11 +145,7 @@ template <typename T> std::ostringstream& Log<T>::Get(TLogLevel level)
template <typename T> Log<T>::~Log()
{
os << std::endl;
#ifdef REST
T::Output( os.str());
#else
T::Output( os.str(),lev);
#endif
T::Output( os.str(),lev); // T::Output( os.str());
}
template <typename T> TLogLevel& Log<T>::ReportingLevel()

View File

@ -23,7 +23,8 @@ class slsReceiver : private virtual slsReceiverDefs {
public:
/**
* Constructor
* creates the tcp interface and the udp class
* Starts up a Receiver server. Reads configuration file, options, and
* assembles a Receiver using TCP and UDP detector interfaces
* @param argc from command line
* @param argv from command line
* @param succecc socket creation was successfull

View File

@ -13,10 +13,6 @@ using namespace std;
#include "UDPInterface.h"
#include "UDPBaseImplementation.h"
#include "UDPStandardImplementation.h"
#ifdef REST
#include "UDPRESTImplementation.h"
#endif
using namespace std;
@ -26,12 +22,6 @@ UDPInterface * UDPInterface::create(string receiver_type){
FILE_LOG(logINFO) << "Starting " << receiver_type;
return new UDPStandardImplementation();
}
#ifdef REST
else if (receiver_type == "REST"){
FILE_LOG(logINFO) << "Starting " << receiver_type;
return new UDPRESTImplementation();
}
#endif
else{
FILE_LOG(logERROR) << "UDP interface not supported, using base implementation";
return new UDPBaseImplementation();

View File

@ -1,381 +0,0 @@
#ifdef SLS_RECEIVER_UDP_FUNCTIONS
/********************************************//**
* @file UDPRESTImplementation.cpp
* @short does all the functions for a receiver, set/get parameters, start/stop etc.
***********************************************/
#include "UDPRESTImplementation.h"
#include <stdlib.h> // exit()
#include <iomanip> // set precision
#include <map> // map
#include <iostream>
#include <string.h>
#include <stdint.h>
#include <sstream>
#include "logger.h"
//#include "utilities.h"
using namespace std;
/*
TODO
+ filePath != getFilePath
+ better state handling. Now it is only IDLE - RUNNING - IDLE
*/
UDPRESTImplementation::UDPRESTImplementation(){
FILE_LOG(logINFO) << "PID: " + __AT__ + " called";
//TODO I do not really know what to do with bottom...
// Default values
isInitialized = true;
rest = NULL;
rest_hostname = "localhost";
rest_port = 8080;
is_main_receiver = false;
}
UDPRESTImplementation::~UDPRESTImplementation(){
delete rest;
}
void UDPRESTImplementation::configure(map<string, string> config_map){
// am I ever getting there?
FILE_LOG(logINFO) << __AT__ << "configure called";
map<string, string>::const_iterator pos;
pos = config_map.find("rest_hostname");
if (pos != config_map.end() ){
rest_hostname = config_map["rest_hostname"];
/*
string host_port_str = pos->second;
std::size_t pos = host_port_str.find(":"); // position of "live" in str
if(pos != string::npos){
istringstream (host_port_str.substr (pos)) >> rest_port;
rest_hostname = host_port_str.substr(0, pos);
std::cout << "YEEEEEEEEEEEEEEEE" << rest_hostname << " " << rest_port << std::endl;
} */
FILE_LOG(logINFO) << "REST hostname " << rest_hostname << std::endl;
}
//initialize_REST();
/*
for(map<string, string>::const_iterator i=config_map.begin(); i != config_map.end(); i++){
std::cout << i->first << " " << i->second<< std::endl;
}
*/
}
string UDPRESTImplementation::get_rest_state(RestHelper * rest/*, string *rest_state*/){
JsonBox::Value answer;
string rest_state = "";
int code = rest->get_json("api/v1/state", &answer);
if ( code != -1 ){
//rest_state = answer["global_state"].getString();
rest_state = answer["state"]["status"].getString();
}
//rest_state = *prs;
std::cout << "REST STATE " << rest_state << std::endl;
return rest_state;
}
void UDPRESTImplementation::initialize_REST(){
FILE_LOG(logDEBUG1) << __AT__ << " called";
FILE_LOG(logINFO) << __AT__ << " REST status is initialized: " + std::string(isInitialized ? "True" : "False");
string rest_state = "";
std::string answer = "";
/*
* HORRIBLE FIX to get the main receiver
* TODO: use detID (from baseclass)
* it i set by the client before calling initialize()
*/
string filename = getFileName();
int code;
//if (filename.substr(filename.length() - 2) == "d0"){
if(detID == 0){
is_main_receiver = true;
}
if (rest_hostname.empty()) {
FILE_LOG(logWARNING) << __AT__ << "can't initialize with empty string or NULL for detectorHostname";
throw;
}
rest = new RestHelper() ;
//std::cout << rest_hostname << " - " << rest_port << std::endl;
rest->init(rest_hostname);
rest->set_connection_params(1, 3);
FILE_LOG(logINFO) << "REST init called";
if (!is_main_receiver){
isInitialized = true;
status = slsReceiverDefs::IDLE;
return;
}
if (isInitialized == true) {
FILE_LOG(logWARNING) << "already initialized, can't initialize several times";
}
else {
FILE_LOG(logINFO) << "with receiverHostName=" << rest_hostname;
try{
rest_state = get_rest_state(rest);
if (rest_state == ""){
FILE_LOG(logERROR) << " REST state returned: " << rest_state;
throw;
}
else{
isInitialized = true;
status = slsReceiverDefs::IDLE;
}
FILE_LOG(logDEBUG1) << "Answer: " << answer;
}
catch(std::string e){
FILE_LOG(logERROR) << __AT__ << ": " << e;
throw;
}
// HORRIBLE FIX to get the main receiver
string filename = getFileName();
int code;
//JsonBox::Object json_object;
//json_object["configfile"] = JsonBox::Value("FILENAME");
JsonBox::Value json_request;
//json_request["configfile"] = "config.py";
json_request["path"] = filePath;
stringstream ss;
string test;
//std::cout << "GetSTring: " << json_request << std::endl;
json_request.writeToStream(ss, false);
//ss << json_request;
ss >> test;
rest_state = get_rest_state(rest);
//code = rest->get_json("api/v1/state", &answer);
//FILE_LOG(logDEBUG1, __AT__ << " state got " + std::string(code) << " " + answer + "\n";
if (rest_state != "INITIALIZED"){
test = "{\"path\":\"" + string( getFilePath() ) + "\", \"n_frames\":10}";
code = rest->post_json("api/v1/initialize", &answer, test);
}
else{
test = "{\"path\":\"" + string( getFilePath() ) + "\"}";
test = "{\"path\":\"" + string( getFilePath() ) + "\", \"n_frames\":10}";
code = rest->post_json("api/v1/configure", &answer, test);
}
//FILE_LOG(logDEBUG1) << " state/configure got " + std::string(code);
rest_state = get_rest_state(rest);
FILE_LOG(logINFO) << " state got " + std::string(rest_state) << "\n";
/*
std::std::cout << string << std::endl; << "---- REST test 3: true, json object "<< std::endl;
JsonBox::Value json_value;
code = rest.get_json("status", &json_value);
std::cout << "JSON " << json_value["status"] << std::endl;
*/
}
FILE_LOG(logDEBUG1) << ": configure() done";
}
/** acquisition functions */
int UDPRESTImplementation::startReceiver(char message[]){
//int i;
FILE_LOG(logINFO) << __AT__ << " starting";
initialize_REST();
FILE_LOG(logINFO) << __AT__ << " initialized";
std::string answer;
int code;
//char *intStr = itoa(a);
//string str = string(intStr);
// TODO: remove hardcode!!!
stringstream ss;
ss << getDynamicRange();
string str_dr = ss.str();
stringstream ss2;
ss2 << getNumberOfFrames();
string str_n = ss2.str();
stringstream ss3;
ss3 << acquisitionPeriod;
string sAP = ss3.str();
string rest_state = "";
std::string request_body = "{\"settings\": {\"bit_depth\": " + str_dr + ", \"n_frames\": " + str_n + ", \"period\": " + sAP + "}}";
//std::string request_body = "{\"settings\": {\"nimages\":1, \"scanid\":999, \"bit_depth\":16}}";
if(is_main_receiver){
FILE_LOG(logDEBUG1) << " sending this configuration body: " << request_body;
code = rest->post_json("api/v1/configure", &answer, request_body);
code = rest->get_json("api/v1/state", &answer);
FILE_LOG(logDEBUG1) << " got: " << answer;
rest_state = get_rest_state(rest);
code = rest->post_json("api/v1/open", &answer);
}
status = RUNNING;
return OK;
}
void UDPRESTImplementation::stopReceiver(){
FILE_LOG(logINFO) << "called";
if(status == RUNNING)
startReadout();
/**
* while(status == TRANSMITTING)
* usleep(5000);
* This has been changed, you check if all the threads are done processing
* and set the final status
*/
//change status
status = IDLE;
FILE_LOG(logDEBUG1) << "exited, status IDLE";
}
void UDPRESTImplementation::startReadout(){
FILE_LOG(logINFO) << " starting";
status = TRANSMITTING;
//kill udp socket to tell the listening thread to push last packet
shutDownUDPSockets();
FILE_LOG(logDEBUG1) << " done";
}
/* FIXME
* Its also called by TCP in case of illegal shut down such as Ctrl + c.
* Upto you what you want to do with it.
*/
void UDPRESTImplementation::shutDownUDPSockets(){
FILE_LOG(logDEBUG1) << "called";
// this is just to be sure, it could be removed
/*
for(int i=0;i<numListeningThreads;i++){
if(udpSocket[i]){
FILE_LOG(logDEBUG1) << __AT__ << " closing UDP socket #" << i;
udpSocket[i]->ShutDownSocket();
delete udpSocket[i];
udpSocket[i] = NULL;
}
}
*/
JsonBox::Value answer;
int code;
string rest_state = "";
//FILE_LOG(logDEBUG1) << __AT__ << " numListeningThreads=" << numListeningThreads;
if (rest == NULL){
FILE_LOG(logWARNING) << "No REST object initialized, closing...";
//return OK;
}
// getting the state
if (is_main_receiver){
FILE_LOG(logWARNING) << "PLEASE WAIT WHILE CHECKING AND SHUTTING DOWN ALL CONNECTIONS!";
rest_state = get_rest_state(rest);
std::cout << rest_state << std::endl;
while (rest_state != "OPEN"){
rest_state = get_rest_state(rest);
std::cout << rest_state << std::endl;
usleep(1000000);
}
//while (rest_state != "TRANSIENT"){
// rest_state = get_rest_state(rest);
// usleep(10000);
//}
code = rest->post_json("api/v1/close", &answer);
rest_state = get_rest_state(rest);
std::cout << rest_state << std::endl;
while (rest_state != "CLOSED"){
rest_state = get_rest_state(rest);
std::cout << rest_state << std::endl;
usleep(1000000);
}
std::cout << "After close" << rest_state << std::endl;
code = rest->post_json("api/v1/reset", &answer);
//rest_state = get_rest_state(rest);
std::cout << rest_state << std::endl;
std::cout << "After reset" << rest_state << std::endl;
}
status = slsReceiverDefs::RUN_FINISHED;
//LEO: not sure it's needed
//delete rest;
FILE_LOG(logDEBUG1) << "finished";
// Leo: how state is handled now?
//return OK;
}
uint64_t UDPRESTImplementation::getTotalFramesCaught() const{
FILE_LOG(logDEBUG1) << " starting";
return (0);
}
#endif

View File

@ -18,51 +18,36 @@ using namespace std;
slsReceiver::slsReceiver(int argc, char *argv[], int &success) {
/**
* Constructor method to start up a Receiver server. Reads configuration file, options, and
* assembles a Receiver using TCP and UDP detector interfaces
*
* @param iarg
*
* @return
*/
slsReceiver::slsReceiver(int argc, char *argv[], int &success):
tcpipInterface (NULL),
udp_interface (NULL)
{
success=OK;
udp_interface = NULL;
tcpipInterface = NULL;
//creating base receiver
// options
map<string, string> configuration_map;
int tcpip_port_no = 1954;
success=OK;
string fname = "";
string udp_interface_type = "standard";
string rest_hostname = "localhost:8081";
udp_interface = NULL;
//parse command line for config
static struct option long_options[] = {
/* These options set a flag. */
// These options set a flag.
//{"verbose", no_argument, &verbose_flag, 1},
/* These options dont set a flag.
We distinguish them by their indices. */
{"type", required_argument, 0, 't'},
{"config", required_argument, 0, 'f'},
{"rx_tcpport", required_argument, 0, 'b'},
{"rest_hostname", required_argument, 0, 'r'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
// These options dont set a flag. We distinguish them by their indices.
{"config", required_argument, 0, 'f'},
{"rx_tcpport", required_argument, 0, 't'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
// getopt_long stores the option index here.
int option_index = 0;
int c=0;
optind = 1;
while ( c != -1 ){
c = getopt_long (argc, argv, "bfhtr", long_options, &option_index);
c = getopt_long (argc, argv, "hf:t:", long_options, &option_index);
/* Detect the end of the options. */
// Detect the end of the options.
if (c == -1)
break;
@ -75,27 +60,16 @@ slsReceiver::slsReceiver(int argc, char *argv[], int &success) {
#endif
break;
case 'b':
case 't':
sscanf(optarg, "%d", &tcpip_port_no);
break;
case 't':
udp_interface_type = optarg;
break;
case 'r':
rest_hostname = optarg;
configuration_map["rest_hostname"] = rest_hostname;
break;
case 'h':
string help_message = """\nSLS Receiver Server\n\n""";
help_message += """usage: slsReceiver --config config_fname [--rx_tcpport port]\n\n""";
help_message += """\t--config:\t configuration filename for SLS Detector receiver\n""";
help_message += """\t--rx_tcpport:\t TCP Communication Port with the client. Default: 1954.\n\n""";
help_message += """\t--rest_hostname:\t Receiver hostname:port. It applies only to REST receivers, and indicates the hostname of the REST backend. Default: localhost:8081.\n\n""";
help_message += """\t--type:\t Type of the receiver. Possible arguments are: standard, REST. Default: standard.\n\n""";
string help_message = "\nSLS Receiver Server\n\n";
help_message += "Usage: slsReceiver [arguments]\nPossible arguments are:\n";
help_message += "\t-f, --config: Configuration filename\n";
help_message += "\t-t, --rx_tcpport: TCP Port with the client. Default: 1954.\n"
"\t Required for multiple receivers\n\n";
FILE_LOG(logINFO) << help_message << endl;
break;
@ -103,9 +77,6 @@ slsReceiver::slsReceiver(int argc, char *argv[], int &success) {
}
}
// if required fname parameter not available, fail
//if (fname == "")
// success = FAIL;
if( !fname.empty() ){
try{
FILE_LOG(logINFO) << "config file name " << fname;
@ -119,11 +90,7 @@ slsReceiver::slsReceiver(int argc, char *argv[], int &success) {
}
if (success==OK){
FILE_LOG(logINFO) << "SLS Receiver starting " << udp_interface_type << " on port " << tcpip_port_no << endl;
#ifdef REST
udp_interface = UDPInterface::create(udp_interface_type);
udp_interface->configure(configuration_map);
#endif
FILE_LOG(logINFO) << "SLS Receiver starting TCP Server on port " << tcpip_port_no << endl;
tcpipInterface = new slsReceiverTCPIPInterface(success, udp_interface, tcpip_port_no);
}
}

View File

@ -776,9 +776,8 @@ int slsReceiverTCPIPInterface::set_detector_type(){
break;
}
if(ret == OK) {
#ifndef REST
if(receiverBase == NULL){
receiverBase = UDPInterface::create("standard");
receiverBase = UDPInterface::create();
if(startAcquisitionCallBack)
receiverBase->registerCallBackStartAcquisition(startAcquisitionCallBack,pStartAcquisition);
if(acquisitionFinishedCallBack)
@ -786,7 +785,6 @@ int slsReceiverTCPIPInterface::set_detector_type(){
if(rawDataReadyCallBack)
receiverBase->registerCallBackRawDataReady(rawDataReadyCallBack,pRawDataReady);
}
#endif
myDetectorType = dr;
ret = receiverBase->setDetectorType(myDetectorType);
retval = myDetectorType;