Requests.cpp 23.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//###########################################################################
// This file is part of LImA, a Library for Image Acquisition
//
// Copyright (C) : 2009-2015
// European Synchrotron Radiation Facility
// BP 220, Grenoble 38043
// FRANCE
//
// This is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//###########################################################################
#include <cstdlib>
#include <cstring>
24
#include <stdio.h>
25
26
27

#include <sstream>

28
#include <json/json.h>
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

#include "eigerapi/Requests.h"
#include "eigerapi/EigerDefines.h"

//Lock class
class Lock
{
public:
  Lock(pthread_mutex_t *aLock,bool aLockFlag = true) :
    _lock(aLock),_lockFlag(false)
  {if(aLockFlag) lock();}
  
  ~Lock() {unLock();}
  inline void lock() 
  {
    if(!_lockFlag)
      while(pthread_mutex_lock(_lock)) ;
    _lockFlag = true;
  }
  inline void unLock()
  {
    if(_lockFlag)
      {
	_lockFlag = false;
	pthread_mutex_unlock(_lock);
      }
  }
private:
  pthread_mutex_t *_lock;
  volatile bool   _lockFlag;
};

using namespace eigerapi;

static const char* CSTR_EIGERCONFIG		= "config";
static const char* CSTR_EIGERSTATUS		= "status";
static const char* CSTR_EIGERSTATUS_BOARD	= "status/board_000";
static const char* CSTR_EIGERCOMMAND		= "command";
67
static const char* CSTR_EIGERFILES		= "files";
68
static const char* CSTR_SUBSYSTEMFILEWRITER	= "filewriter";
69
static const char* CSTR_SUBSYSTEMSTREAM		= "stream";
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
static const char* CSTR_SUBSYSTEMDETECTOR	= "detector";
static const char* CSTR_DATA			= "data";
static const char* CSTR_EIGERVERSION		= "version";
static const char* CSTR_EIGERAPI		= "api";

struct ResourceDescription
{
   ResourceDescription(const char* name,
                       const char* subsystem=CSTR_SUBSYSTEMDETECTOR,
                       const char* location=CSTR_EIGERCONFIG) :
     m_name(name),
     m_subsystem(subsystem),
     m_location(location)
  {};
  
  std::string build_url(const std::ostringstream& base_url,
			const std::ostringstream& api);
  
  const char*       m_name;
  const char*       m_subsystem;   
  const char*       m_location;
  std::string	    m_url;
};

struct CommandIndex
{
  Requests::COMMAND_NAME	name;
  ResourceDescription		desc;
};

static CommandIndex CommandsDescription[] = {
  {Requests::INITIALIZE,	{"initialize",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERCOMMAND}},
  {Requests::ARM,		{"arm",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERCOMMAND}},
  {Requests::DISARM,		{"disarm",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERCOMMAND}},
  {Requests::TRIGGER,		{"trigger",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERCOMMAND}},
  {Requests::CANCEL,		{"cancel",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERCOMMAND}},
  {Requests::ABORT,		{"abort",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERCOMMAND}},
107
  {Requests::FILEWRITER_CLEAR,  {"clear",CSTR_SUBSYSTEMFILEWRITER,CSTR_EIGERCOMMAND}},
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
};

const char* get_cmd_name(Requests::COMMAND_NAME cmd_name)
{
  int nb_cmd = sizeof(CommandsDescription) / sizeof(CommandIndex);
  for(int i = 0;i < nb_cmd;++i)
    {
      if(CommandsDescription[i].name == cmd_name)
	return CommandsDescription[i].desc.m_name;
    }
  return "not found";		// weired
}
struct ParamIndex
{
  Requests::PARAM_NAME	name;
  ResourceDescription	desc;
};

ParamIndex ParamDescription[] = {
  // Detector Read only values
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  {Requests::TEMP,				{"th0_temp",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERSTATUS_BOARD}},
  {Requests::HUMIDITY,				{"th0_humidity",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERSTATUS_BOARD}},
  {Requests::DETECTOR_STATUS,			{"state",CSTR_SUBSYSTEMDETECTOR,CSTR_EIGERSTATUS}},
  {Requests::PIXELDEPTH,			{"bit_depth_readout"}},
  {Requests::X_PIXEL_SIZE,			{"x_pixel_size"}},
  {Requests::Y_PIXEL_SIZE,			{"y_pixel_size"}},
  {Requests::DETECTOR_WITDH,			{"x_pixels_in_detector"}},
  {Requests::DETECTOR_HEIGHT,			{"y_pixels_in_detector"}},
  {Requests::DESCRIPTION,			{"description"}},
  {Requests::DETECTOR_NUMBER,			{"detector_number"}},
  {Requests::DETECTOR_READOUT_TIME,		{"detector_readout_time"}},
  {Requests::DATA_COLLECTION_DATE,		{"data_collection_date"}},
  {Requests::SOFTWARE_VERSION,			{"software_version"}},

142
  // Detector Read/Write settings
143
144
145
146
147
148
149
150
151
152
153
154
155
156
  {Requests::EXPOSURE,				{"count_time"}},
  {Requests::FRAME_TIME,			{"frame_time"}},
  {Requests::TRIGGER_MODE,			{"trigger_mode"}},
  {Requests::COUNTRATE_CORRECTION,		{"countrate_correction_applied"}},
  {Requests::FLATFIELD_CORRECTION,		{"flatfield_correction_applied"}},
  {Requests::EFFICIENCY_CORRECTION,		{"efficiency_correction_applied"}},
  {Requests::PIXEL_MASK,			{"pixel_mask_applied"}},
  {Requests::THRESHOLD_ENERGY,			{"threshold_energy"}},
  {Requests::VIRTUAL_PIXEL_CORRECTION,		{"virtual_pixel_correction_applied"}},
  {Requests::PHOTON_ENERGY,			{"photon_energy"}},
  {Requests::NIMAGES,				{"nimages"}},
  {Requests::NTRIGGER,				{"ntrigger"}},
  {Requests::AUTO_SUMMATION,			{"auto_summation"}},

157
  // Filewriter settings
158
159
160
161
162
163
164
165
  {Requests::FILEWRITER_MODE,			{"mode",CSTR_SUBSYSTEMFILEWRITER}},
  {Requests::FILEWRITER_COMPRESSION,		{"compression_enabled", CSTR_SUBSYSTEMFILEWRITER}},
  {Requests::FILEWRITER_NAME_PATTERN,		{"name_pattern", CSTR_SUBSYSTEMFILEWRITER}},
  {Requests::NIMAGES_PER_FILE,			{"nimages_per_file", CSTR_SUBSYSTEMFILEWRITER}},
  {Requests::FILEWRITER_STATUS,			{"state", CSTR_SUBSYSTEMFILEWRITER, CSTR_EIGERSTATUS}},
  {Requests::FILEWRITER_ERROR,			{"error", CSTR_SUBSYSTEMFILEWRITER, CSTR_EIGERSTATUS}},
  {Requests::FILEWRITER_TIME,			{"time", CSTR_SUBSYSTEMFILEWRITER, CSTR_EIGERSTATUS}},
  {Requests::FILEWRITER_BUFFER_FREE,		{"buffer_free", CSTR_SUBSYSTEMFILEWRITER, CSTR_EIGERSTATUS}},
166
167
  {Requests::FILEWRITER_LS,			{"", CSTR_SUBSYSTEMFILEWRITER, CSTR_EIGERFILES}},
  {Requests::FILEWRITER_LS2,			{"files", CSTR_SUBSYSTEMFILEWRITER, CSTR_EIGERSTATUS}},
168
169
170
171
172
173
  // Stream settings
  {Requests::STREAM_MODE,			{"mode", CSTR_SUBSYSTEMSTREAM}},
  {Requests::STREAM_HEADER_DETAIL,		{"header_detail", CSTR_SUBSYSTEMSTREAM}},
  // Saving Header
  {Requests::HEADER_BEAM_CENTER_X,		{"beam_center_x"}},
  {Requests::HEADER_BEAM_CENTER_Y,		{"beam_center_y"}},
174
175
  {Requests::HEADER_CHI_INCREMENT,		{"chi_increment"}},
  {Requests::HEADER_CHI_START,			{"chi_start"}},
176
  {Requests::HEADER_DETECTOR_DISTANCE,		{"detector_distance"}},
177
178
179
180
181
182
  {Requests::HEADER_KAPPA_INCREMENT,		{"kappa_increment"}},
  {Requests::HEADER_KAPPA_START,		{"kappa_start"}},
  {Requests::HEADER_OMEGA_INCREMENT,		{"omega_increment"}},
  {Requests::HEADER_OMEGA_START,		{"omega_start"}},
  {Requests::HEADER_PHI_INCREMENT,		{"phi_increment"}},
  {Requests::HEADER_PHI_START,			{"phi_start"}},
183
  {Requests::HEADER_WAVELENGTH,			{"wavelength"}},
184
185
  // Compression
  {Requests::COMPRESSION_TYPE,			{"compression"}},
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
};

const char* get_param_name(Requests::PARAM_NAME param_name)
{
  int nb_param = sizeof(ParamDescription) / sizeof(ParamIndex);
  for(int i = 0;i < nb_param;++i)
    {
      if(ParamDescription[i].name == param_name)
	return ParamDescription[i].desc.m_name;
    }
  return "not found";		// weired
}

std::string ResourceDescription::build_url(const std::ostringstream& base_url,
					   const std::ostringstream& api)
{
  std::ostringstream url;
  if(!m_location)
    url << base_url.str() << m_subsystem << api.str() << m_name;
  else    
    url << base_url.str() << m_subsystem << api.str() << m_location << '/' << m_name;
207
  return url.str();
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
}

// Requests class
Requests::Requests(const std::string& address) :
  m_address(address)
{
  std::ostringstream base_url;
  base_url << "http://" << address << '/';

  std::ostringstream url;
  url  << base_url.str() << CSTR_SUBSYSTEMDETECTOR << '/'
       << CSTR_EIGERAPI << '/' << CSTR_EIGERVERSION << '/';
  
  std::shared_ptr<Param> version_request(new Param(url.str()));
  version_request->_fill_get_request();
  m_loop.add_request(version_request);
  
  Requests::Param::Value value = version_request->get();
  std::string& api_version = value.string_val;
  
  std::ostringstream api;
  api << '/' << CSTR_EIGERAPI << '/' << api_version << '/';
  
  // COMMANDS URL CACHE
  int nb_cmd = sizeof(CommandsDescription) / sizeof(CommandIndex);
  for(int i = 0;i < nb_cmd;++i)
    {
      CommandIndex& index = CommandsDescription[i];
      m_cmd_cache_url[index.name] = index.desc.build_url(base_url,api);
    }
  // PARAMS URL CACHE
  int nb_params = sizeof(ParamDescription) / sizeof(ParamIndex);
  for(int i = 0;i < nb_params;++i)
    {
      ParamIndex& index = ParamDescription[i];
      m_param_cache_url[index.name] = index.desc.build_url(base_url,api);
    }
}

Requests::~Requests()
{
}

std::shared_ptr<Requests::Command>
Requests::get_command(Requests::COMMAND_NAME cmd_name)
{
  CACHE_TYPE::iterator cmd_url = m_cmd_cache_url.find(cmd_name);
  if(cmd_url == m_cmd_cache_url.end())
    THROW_EIGER_EXCEPTION(RESOURCE_NOT_FOUND,get_cmd_name(cmd_name));

  std::shared_ptr<Requests::Command> cmd(new Command(cmd_url->second));
  cmd->_fill_request();
  m_loop.add_request(cmd);
261
  return cmd;
262
263
264
265
266
267
268
269
}

std::shared_ptr<Requests::Param>
Requests::get_param(Requests::PARAM_NAME param_name)
{
  std::shared_ptr<Requests::Param> param = _create_get_param(param_name);

  m_loop.add_request(param);
270
  return param;
271
272
273
274
275
276
277
}

#define GENERATE_GET_PARAM()						\
  std::shared_ptr<Requests::Param> param = _create_get_param(param_name); \
  param->_set_return_value(ret_value);					\
									\
  m_loop.add_request(param);						\
278
  return param;							\
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

std::shared_ptr<Requests::Param>
Requests::get_param(Requests::PARAM_NAME param_name,bool& ret_value)
{
  GENERATE_GET_PARAM();
}

std::shared_ptr<Requests::Param>
Requests::get_param(Requests::PARAM_NAME param_name,
		    double& ret_value)
{
  GENERATE_GET_PARAM();
}

std::shared_ptr<Requests::Param>
Requests::get_param(Requests::PARAM_NAME param_name,
		    int& ret_value)
{
  GENERATE_GET_PARAM();
}

std::shared_ptr<Requests::Param>
Requests::get_param(Requests::PARAM_NAME param_name,
		    unsigned int& ret_value)
{
  GENERATE_GET_PARAM();
}

std::shared_ptr<Requests::Param>
Requests::get_param(Requests::PARAM_NAME param_name,
		    std::string& ret_value)
{
  GENERATE_GET_PARAM();
}

std::shared_ptr<Requests::Param>
Requests::_create_get_param(Requests::PARAM_NAME param_name)
{
  CACHE_TYPE::iterator param_url = m_param_cache_url.find(param_name);
  if(param_url == m_param_cache_url.end())
    THROW_EIGER_EXCEPTION(RESOURCE_NOT_FOUND,get_param_name(param_name));
  
  std::shared_ptr<Requests::Param> param(new Param(param_url->second));
  param->_fill_get_request();
323
  return param;
324
325
326
327
328
329
330
331
332
333
334
335
336
}

template <class T>
std::shared_ptr<Requests::Param>
Requests::_set_param(Requests::PARAM_NAME param_name,const T& value)
{
  CACHE_TYPE::iterator param_url = m_param_cache_url.find(param_name);
  if(param_url == m_param_cache_url.end())
    THROW_EIGER_EXCEPTION(RESOURCE_NOT_FOUND,get_param_name(param_name));

  std::shared_ptr<Requests::Param> param(new Param(param_url->second));
  param->_fill_set_request(value);
  m_loop.add_request(param);
337
  return param;
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
}

std::shared_ptr<Requests::Param>
Requests::set_param(Requests::PARAM_NAME name,bool value)
{
  return _set_param(name,value);
}

std::shared_ptr<Requests::Param>
Requests::set_param(PARAM_NAME name,double value)
{
  return _set_param(name,value);
}

std::shared_ptr<Requests::Param>
Requests::set_param(PARAM_NAME name,int value)
{
  return _set_param(name,value);
}

std::shared_ptr<Requests::Param>
Requests::set_param(PARAM_NAME name,unsigned int value)
{
  return _set_param(name,value);
}

std::shared_ptr<Requests::Param>
Requests::set_param(PARAM_NAME name,const std::string& value)
{
  return _set_param(name,value);
}

std::shared_ptr<Requests::Param>
Requests::set_param(PARAM_NAME name,const char* value)
{
  return _set_param(name,value);
}


std::shared_ptr<Requests::Transfer> 
Requests::start_transfer(const std::string& src_filename,
			  const std::string& dest_path,
			  bool delete_after_transfer)
{
  std::ostringstream url;
  url << "http://" << m_address << '/' << CSTR_DATA << '/'
      << src_filename;
  
  std::shared_ptr<Transfer> transfer(new Transfer(*this,
						  url.str(),
						  dest_path,
						  delete_after_transfer));
  m_loop.add_request(transfer);
391
  return transfer;
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
}

std::shared_ptr<CurlLoop::FutureRequest>
Requests::delete_file(const std::string& filename,bool full_url)
{
  std::ostringstream url;
  if(!full_url)
    url << "http://" << m_address << '/' << CSTR_DATA << '/'
	<< filename;
  else
    url << filename;

 std::shared_ptr<CurlLoop::FutureRequest> 
   delete_req(new CurlLoop::FutureRequest(url.str()));
 CURL* handle = delete_req->get_handle();
 curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, "DELETE"); 
 m_loop.add_request(delete_req);
409
 return delete_req;
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
}

void Requests::cancel(std::shared_ptr<CurlLoop::FutureRequest> req)
{
  m_loop.cancel_request(req);
}
//Class Command
Requests::Command::Command(const std::string& url) :
  CurlLoop::FutureRequest(url)
{
  m_data[0] = '\0';
}

Requests::Command::~Command()
{
}

void Requests::Command::_fill_request()
{
  curl_easy_setopt(m_handle,CURLOPT_CUSTOMREQUEST, "PUT");
  curl_easy_setopt(m_handle,CURLOPT_WRITEFUNCTION,_write_callback);
  curl_easy_setopt(m_handle,CURLOPT_WRITEDATA,this);
}

size_t Requests::Command::_write_callback(char *ptr,size_t size,
					  size_t nmemb,Requests::Command *cmd)
{
  int size_to_copy = std::min(size * nmemb,sizeof(m_data));
  memcpy(cmd->m_data,ptr,size_to_copy);
  cmd->m_data[size_to_copy] = '\0';
  return size_to_copy;
}

int Requests::Command::get_serie_id()
{
  Json::Value root;
  Json::Reader reader;
  if(!reader.parse(m_data,root))
    THROW_EIGER_EXCEPTION(eigerapi::JSON_PARSE_FAILED,"");

  int seq_id = root.get("sequence id", -1).asInt();
  return seq_id;
}
//Class Param

Requests::Param::Param(const std::string& url) :
  CurlLoop::FutureRequest(url),
  m_data_buffer(NULL),
  m_data_size(0),
  m_data_memorysize(0),
  m_headers(NULL),
  m_return_value(NULL)
{
}

Requests::Param::~Param()
{
  if(m_data_memorysize)
    free(m_data_buffer);
  
  if(m_headers)
    curl_slist_free_all(m_headers);
}
473
474
475

Requests::Param::Value Requests::Param::_get(double timeout,bool lock,
					     const char* param_name)
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
{
  wait(timeout,lock);
  //check rx data
  if(!m_data_buffer)
    THROW_EIGER_EXCEPTION("No data received","");

  if(m_data_size == m_data_memorysize) // need to add an extra char
    {
      int alloc_size = (m_data_memorysize + 1024) & ~1023;
      m_data_buffer = (char*)realloc(m_data_buffer,alloc_size);
      m_data_memorysize = alloc_size;
    }

  m_data_buffer[m_data_size] = '\0'; // string ending

  //- Json decoding to return the wanted data
  Json::Value  root;
  Json::Reader reader;

  if (!reader.parse(m_data_buffer, root)) 
    THROW_EIGER_EXCEPTION(eigerapi::JSON_PARSE_FAILED,"");
  Value value;
498
  std::string json_type;
499
  bool is_list = root.isArray() || root.get(param_name, "no_value").isArray();
500
501
502
503
504
  if (!is_list) {
    json_type = root.get("value_type", "dummy").asString();
    is_list = (json_type == "list");
  }
  if(is_list)
505
506
    {
      value.type = Requests::Param::STRING_ARRAY;
507
      Json::Value& array = root.isArray() ? root : root[param_name];
508
      int array_size = array.size();
509
      for(int i = 0;i < array_size;++i)
510
	value.string_array.push_back(array[i].asString());
511
512
513
514
515
516
517
518
    }
  else
    {
      //- supported types by dectris are:
      //- bool, float, int, string or a list of float or int
      if (json_type == "bool")
	{
	  value.type = Requests::Param::BOOL;
519
	  value.data.bool_val = root.get(param_name, "no_value").asBool();
520
521
522
523
524
	}
      else if (json_type == "float")
	{
	  //- asFloat is not supported by jsoncpp
	  value.type = Requests::Param::DOUBLE;
525
	  value.data.double_val = root.get(param_name, -1.0).asDouble();
526
527
528
529
	}
      else if (json_type == "int")
	{
	  value.type = Requests::Param::INT;
530
	  value.data.int_val = root.get(param_name, -1).asInt();
531
532
533
534
	}
      else if (json_type == "uint")
	{
	  value.type = Requests::Param::UNSIGNED;
535
	  value.data.unsigned_val = (int) root.get(param_name, -1).asInt();
536
537
538
539
	}
      else if (json_type == "string")
	{
	  value.type = Requests::Param::STRING;
540
	  value.string_val = root.get(param_name,"no_value").asString();
541
542
543
544
545
546
547
548
549
550
	}
      else
	{
	  THROW_EIGER_EXCEPTION(eigerapi::DATA_TYPE_NOT_HANDLED,
				json_type.c_str());
	}
    }
  return value;
}

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
Requests::Param::Value Requests::Param::get(double timeout,bool lock)
{
  return _get(timeout,lock,"value");
}

Requests::Param::Value Requests::Param::get_min(double timeout,bool lock)
{
  return _get(timeout,lock,"min");
}

Requests::Param::Value Requests::Param::get_max(double timeout,bool lock)
{
  return _get(timeout,lock,"max");
}

566
567
568
569
570
Requests::Param::Value Requests::Param::get_allowed_values(double timeout,bool lock)
{
  return _get(timeout,lock,"allowed_values");
}

571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
void Requests::Param::_fill_get_request()
{
  curl_easy_setopt(m_handle,CURLOPT_WRITEFUNCTION,_write_callback);
  curl_easy_setopt(m_handle,CURLOPT_WRITEDATA,this);
}

template <class T>
void Requests::Param::_fill_set_request(const T& value)
{
  Json::Value root;
  root["value"] = value;
  Json::FastWriter writer;
  std::string json_struct = writer.write(root);

  m_headers = curl_slist_append(m_headers, "Accept: application/json");
  m_headers = curl_slist_append(m_headers, "Content-Type: application/json;charset=utf-8");

  curl_easy_setopt(m_handle, CURLOPT_HTTPHEADER, m_headers);
  curl_easy_setopt(m_handle, CURLOPT_CUSTOMREQUEST, "PUT"); 
590
  curl_easy_setopt(m_handle, CURLOPT_FAILONERROR, true);
591
592
593
594

  m_data_buffer = strdup(json_struct.c_str()),m_data_memorysize = json_struct.length();
  curl_easy_setopt(m_handle, CURLOPT_POSTFIELDS, m_data_buffer); // data goes here
  curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE,json_struct.length()); // data length
595
596
597

  curl_easy_setopt(m_handle,CURLOPT_WRITEFUNCTION,_write_callback);
  curl_easy_setopt(m_handle,CURLOPT_WRITEDATA,this);
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
}

void Requests::Param::_set_return_value(bool& ret_value)
{
  m_return_value = &ret_value;
  m_return_type = BOOL;
}
void Requests::Param::_set_return_value(double& ret_value)
{
  m_return_value = &ret_value;
  m_return_type = DOUBLE;
}
void Requests::Param::_set_return_value(int& ret_value)
{
  m_return_value = &ret_value;
  m_return_type = INT;
}
void Requests::Param::_set_return_value(unsigned int& ret_value)
{
  m_return_value = &ret_value;
  m_return_type = UNSIGNED;
}
void Requests::Param::_set_return_value(std::string& ret_value)
{
  m_return_value = &ret_value;
  m_return_type = STRING;
}

void Requests::Param::_request_finished()
{
  if(m_status == CANCEL) return;

  std::string error_string;
  if(m_return_value)
    {
      Value value;
      try {value = get(0,false);}
      catch(EigerException &e)
	{
	  error_string = e.what();
	  goto error;
	}

      switch(m_return_type)
	{
	case BOOL:
	  {
	    bool *retrun_val = (bool*)m_return_value;
	    switch(value.type)
	      {
	      case BOOL:
		*retrun_val = value.data.bool_val;break;
	      case INT:
		*retrun_val = value.data.int_val;break;
	      case UNSIGNED:
		*retrun_val = value.data.unsigned_val;break;
	      default:
		error_string = "Rx value is not a bool";
		goto error;
	      }
	    break;
	  }
	case DOUBLE:
	  {
	    double *retrun_val = (double*)m_return_value;
	    switch(value.type)
	      {
	      case INT:
		*retrun_val = value.data.int_val;break;
	      case UNSIGNED:
		*retrun_val = value.data.unsigned_val;break;
	      case DOUBLE:
		*retrun_val = value.data.double_val;break;
	      default:
		error_string = "Rx value is not a double";
		goto error;
	      }
	    break;
	  }
	case INT:
	  {
	    int *retrun_val = (int*)m_return_value;
	    switch(value.type)
	      {
	      case INT:
		*retrun_val = value.data.int_val;break;
	      default:
		error_string = "Rx value is not a integer";
		goto error;
	      }
	    break;
	  }
	case UNSIGNED:
	  {
	    unsigned int *retrun_val = (unsigned int*)m_return_value;
	    switch(value.type)
	      {
	      case INT:
		*retrun_val = value.data.int_val;break;
	      case UNSIGNED:
		*retrun_val = value.data.unsigned_val;break;
	      default:
		error_string = "Rx value is not a unsigned integer";
		goto error;
	      }
	    break;
	  }
	case STRING:
	  {
	    std::string *retrun_val = (std::string*)m_return_value;
	    switch(value.type)
	      {
	      case STRING:
		*retrun_val = value.string_val;break;
	      default:
		error_string = "Rx value is not a string";
		goto error;
	      }
	    break;
	  }
	default:
	  error_string = "Value type not yet managed";
	  goto error;
	}
    }
  return;

 error:
  if(m_error_code.empty())
    m_error_code = error_string + "(" + m_url + ")";
  else
    {
      m_error_code += "\n";
      m_error_code += error_string;
    }
  m_status = ERROR;
}

size_t Requests::Param::_write_callback(char *ptr,size_t size,
					size_t nmemb,void *userdata)
{
  Param *t = (Param*)userdata;
  int size_to_copy = size * nmemb;
  if(size_to_copy > 0)
    {
      int request_memory_size = t->m_data_size + size_to_copy;
      if(request_memory_size > t->m_data_memorysize) // realloc
	{
	  int alloc_size = (request_memory_size + 4095) & ~4095;
	  t->m_data_buffer = (char*)realloc(t->m_data_buffer,alloc_size);
	  t->m_data_memorysize = alloc_size;
	}
      memcpy(t->m_data_buffer + t->m_data_size,ptr,size_to_copy);
      t->m_data_size += size_to_copy;
    }
  return size_to_copy;
}

/*----------------------------------------------------------------------------
			   Class Transfer
----------------------------------------------------------------------------*/
Requests::Transfer::Transfer(Requests& requests,
			     const std::string& url,
			     const std::string& target_path,
762
763
			     bool delete_after_transfer,
			     int buffer_write_size) :
764
765
766
767
768
  CurlLoop::FutureRequest(url),
  m_requests(requests),
  m_delete_after_transfer(delete_after_transfer),
  m_download_size(0)
{
769
770
  if(posix_memalign(&m_buffer,4*1024,buffer_write_size))
    THROW_EIGER_EXCEPTION("Can't allocate write buffer memory","");
771
  m_target_file = fopen(target_path.c_str(),"w+");
772
773
  if(!m_target_file)
    {
774
      free(m_buffer);
775
776
      char str_errno[1024];
      strerror_r(errno,str_errno,sizeof(str_errno));
777
778
779
      std::ostringstream error_buffer;
      error_buffer << "Can't open destination file " << target_path;
      THROW_EIGER_EXCEPTION(error_buffer.str().c_str(), str_errno);
780
    }
781
  setbuffer(m_target_file,(char*)m_buffer,buffer_write_size);
782
783
784
785
786
787
788
  curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, _write);
  curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, this);
}
Requests::Transfer::~Transfer()
{
  if(m_target_file)
    fclose(m_target_file);
789
  free(m_buffer);
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
}

size_t
Requests::Transfer::_write(void *ptr, size_t size,
			    size_t nmemb, Requests::Transfer *transfer)
{

  FILE *stream = transfer->m_target_file;
  size_t write_size = fwrite(ptr, size, nmemb, stream);

  Lock lock(&transfer->m_lock);
  if(write_size > 0)
    transfer->m_download_size += size * nmemb;

  return write_size;
}

void Requests::Transfer::_request_finished()
{
  fclose(m_target_file);m_target_file = NULL;
  // start new request to delete the file
  if(m_status == FutureRequest::OK &&
     m_delete_after_transfer)
    m_requests.delete_file(m_url,true);
}