nmxptool.c 49.4 KB
Newer Older
Matteo Quintiliani's avatar
Matteo Quintiliani committed
1 2 3 4 5 6 7 8 9
/*! \file
 *
 * \brief Nanometrics Protocol Tool
 *
 * Author:
 * 	Matteo Quintiliani
 * 	Istituto Nazionale di Geofisica e Vulcanologia - Italy
 *	quintiliani@ingv.it
 *
10
 * $Id: nmxptool.c,v 1.231 2010-09-15 13:14:49 mtheo Exp $
Matteo Quintiliani's avatar
Matteo Quintiliani committed
11
 *
Matteo Quintiliani's avatar
Matteo Quintiliani committed
12 13
 */

14
#include "config.h"
15 16 17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
18
#include <errno.h>
19
#include <signal.h>
20

21 22 23
#include <sys/stat.h>
#include <unistd.h>

24 25 26 27
#include <nmxp.h>
#include "nmxptool_getoptlong.h"
#include "nmxptool_chanseq.h"
#include "nmxptool_sigcondition.h"
28
#include <nmxptool_listen.h>
29

30 31 32
#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#else
33
#warning Requests of channels could not be efficient because they do not use a separate thread. 
34 35
#endif

36 37 38 39
#ifdef HAVE_WINDOWS_H
#include <windows.h>
#endif

40
#ifdef HAVE_EARTHWORMOBJS
41
#include "nmxptool_ew.h"
42
#endif
43

44 45 46
#ifdef HAVE_LIBMSEED
#include <libmseed.h>
#endif
47

48 49
#ifdef HAVE___SRC_SEEDLINK_PLUGIN_H
#include "seedlink_plugin.h"
50 51
#endif

52 53
#define TIMES_FLOW_EXIT 100

54 55
int if_dap_condition_only_one_time = 0;

56 57 58 59 60 61 62 63 64
#define DAP_CONDITION(params_struct) (params_struct.start_time != 0.0 || params_struct.delay > 0)

#define EXIT_CONDITION_PRELIM (!nmxptool_sigcondition_read()  &&  !ew_check_flag_terminate  &&  !if_dap_condition_only_one_time)
#ifdef HAVE_LIBMSEED
#define EXIT_CONDITION ( EXIT_CONDITION_PRELIM  &&  data_seed.err_general==0 )
#else
#define EXIT_CONDITION ( EXIT_CONDITION_PRELIM )
#endif
		    
65 66
#define CURRENT_LOCATION ( (params.location)? params.location : DEFAULT_NULL_LOCATION )
#define LOCCODE_OR_CURRENT_LOCATION ( (location_code[0] != 0)? location_code : CURRENT_LOCATION )
67

68 69 70
#define CURRENT_NETWORK ( (params.network)? params.network : DEFAULT_NETWORK )
#define NETCODE_OR_CURRENT_NETWORK ( (network_code[0] != 0)? network_code : CURRENT_NETWORK )

71
static void ShutdownHandler(int sig);
72
static void nmxptool_AlarmHandler(int sig);
73
static void CloseConnectionHandler(int sig);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
74

Matteo Quintiliani's avatar
Matteo Quintiliani committed
75 76 77 78 79
void flushing_raw_data_stream();

void *nmxptool_print_info_raw_stream(void *arg);
int nmxptool_print_seq_no(NMXP_DATA_PROCESS *pd);
void nmxptool_str_time_to_filename(char *str_time);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
80

81
#ifdef HAVE_LIBMSEED
Matteo Quintiliani's avatar
Matteo Quintiliani committed
82
int nmxptool_write_miniseed(NMXP_DATA_PROCESS *pd);
83 84
int nmxptool_log_miniseed(const char *s);
int nmxptool_logerr_miniseed(const char *s);
85 86
#endif

87
#ifdef HAVE___SRC_SEEDLINK_PLUGIN_C
Matteo Quintiliani's avatar
Matteo Quintiliani committed
88
int nmxptool_send_raw_depoch(NMXP_DATA_PROCESS *pd);
89 90
#endif

91 92 93 94 95 96 97
#ifdef HAVE_LIBMSEED
#ifdef HAVE___SRC_SEEDLINK_PLUGIN_C
void nmxptool_msr_send_mseed_handler (char *record, int reclen, void *handlerdata);
int nmxptool_msr_send_mseed(NMXP_DATA_PROCESS *pd);
#endif
#endif

Matteo Quintiliani's avatar
Matteo Quintiliani committed
98
#ifdef HAVE_PTHREAD_H
99
pthread_mutex_t mutex_sendAddTimeSeriesChannel = PTHREAD_MUTEX_INITIALIZER;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
100
pthread_t thread_request_channels;
101
pthread_attr_t attr_request_channels;
102
void *status_thread;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
103 104
void *p_nmxp_sendAddTimeSeriesChannel(void *arg);
#endif
Matteo Quintiliani's avatar
Matteo Quintiliani committed
105

106 107 108 109
#ifdef HAVE_PTHREAD_H
pthread_t thread_socket_listen;
pthread_attr_t attr_socket_listen;
void *status_thread_socket_listen;
110
int already_listen = 0;
111 112
#endif

Matteo Quintiliani's avatar
Matteo Quintiliani committed
113

114
/* Global variable for main program and handling terminitation program */
115 116 117
NMXPTOOL_PARAMS params={0};


118
int naqssock = 0;
119
int flag_force_close_connection = 0;
120 121
FILE *outfile = NULL;
NMXP_CHAN_LIST *channelList = NULL;
122
NMXP_CHAN_LIST_NET *channelList_subset = NULL;
123
NMXP_CHAN_LIST_NET *channelList_subset_waste = NULL;
124
NMXPTOOL_CHAN_SEQ *channelList_Seq = NULL;
125
NMXP_META_CHAN_LIST *meta_channelList = NULL;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
126 127 128
int n_func_pd = 0;
int (*p_func_pd[NMXP_MAX_FUNC_PD]) (NMXP_DATA_PROCESS *);

129 130 131 132 133 134 135

#ifdef HAVE_LIBMSEED
/* Mini-SEED variables */
NMXP_DATA_SEED data_seed;
MSRecord *msr_list_chan[MAX_N_CHAN];
#endif

136
int ew_check_flag_terminate = 0;
137

138
int main (int argc, char **argv) {
139
    int32_t connection_time;
140
    int request_SOCKET_OK;
141 142 143 144
#ifdef HAVE_LIBMSEED
    int i_chan =0;
#endif
    int cur_chan = 0;
145
    int to_cur_chan = 0;
146
    int request_chan;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
147
    int exitpdscondition;
148
    int exitdapcondition;
149
    time_t timeout_for_channel;
150 151 152

    int time_to_sleep = 0;

153 154
    char str_start_time[200] = "";
    char str_end_time[200] = "";
155 156

    NMXP_MSG_SERVER type;
157
    char buffer[NMXP_MAX_LENGTH_DATA_BUFFER]={0};
158
    int32_t length;
159
    int ret;
160
    int main_ret = 0;
161

162
    int pd_null_count = 0;
163
    int timeoutrecv_warning = 300; /* 5 minutes */
164

165 166
    int times_flow = 0;

167
    int recv_errno = 0; 
Matteo Quintiliani's avatar
Matteo Quintiliani committed
168
#ifdef HAVE_EARTHWORMOBJS
169
    char *recv_errno_str;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
170
#endif
171
  
172
    char filename[500] = "";
173
    char station_code[20] = "", channel_code[20] = "", network_code[20] = "", location_code[20] = "";
174

Matteo Quintiliani's avatar
Matteo Quintiliani committed
175
    char cur_after_start_time_str[1024];
176 177
    double cur_after_start_time = DEFAULT_BUFFERED_TIME;
    int skip_current_packet = 0;
178

179
    double default_start_time = 0.0;
180
    char start_time_str[30], end_time_str[30], default_start_time_str[30];
181

182
    NMXP_DATA_PROCESS *pd = NULL;
183

184 185 186 187
#ifdef HAVE_PTHREAD_H
    pthread_mutex_init(&mutex_sendAddTimeSeriesChannel, NULL);
#endif

188
#ifndef HAVE_WINDOWS_H
Matteo Quintiliani's avatar
Matteo Quintiliani committed
189 190 191
    /* Signal handling, use POSIX calls with standardized semantics */
    struct sigaction sa;

192
    sa.sa_handler = nmxptool_AlarmHandler;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
193 194 195
    sa.sa_flags = SA_RESTART;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGALRM, &sa, NULL);
196

197 198 199
    sa.sa_handler = CloseConnectionHandler;
    sigaction(SIGUSR1, &sa, NULL);

200
    sa.sa_handler = ShutdownHandler;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
201 202 203 204 205 206 207
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGQUIT, &sa, NULL); 
    sigaction(SIGTERM, &sa, NULL);

    sa.sa_handler = SIG_IGN;
    sigaction(SIGHUP, &sa, NULL);
    sigaction(SIGPIPE, &sa, NULL); 
208
#else
Matteo Quintiliani's avatar
Matteo Quintiliani committed
209 210
    /* Signal handling, use function signal() */

211
    /*
212
    signal(SIGALRM, nmxptool_AlarmHandler);
213
    */
214 215

    signal(SIGINT, ShutdownHandler);
216
    /*
217
    signal(SIGQUIT, ShutdownHandler);
218
    */
219 220
    signal(SIGTERM, ShutdownHandler);

221
    /*
222 223
    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
224
    */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
225 226
#endif

227
    nmxptool_sigcondition_init();
228

Matteo Quintiliani's avatar
Matteo Quintiliani committed
229
    /* Default is normal output */
230
    nmxp_log(NMXP_LOG_SET, NMXP_LOG_D_NULL);
231 232 233 234 235 236

    /* Initialize params from argument values */
    if(nmxptool_getopt_long(argc, argv, &params) != 0) {
	return 1;
    }

237
    if(params.ew_configuration_file) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
238 239

#ifdef HAVE_EARTHWORMOBJS
240

241 242
	nmxp_log_init(nmxptool_ew_logit_msg, nmxptool_ew_logit_err);

Matteo Quintiliani's avatar
Matteo Quintiliani committed
243
	nmxptool_ew_configure(argv, &params);
244

Matteo Quintiliani's avatar
Matteo Quintiliani committed
245 246 247 248
	/* Check consistency of params */
	if(nmxptool_check_params(&params) != 0) {
	    return 1;
	}
249

250 251 252
#else
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_ANY, "Earthworm feature has not been enabled in compilation!\n");
	return 1;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
253
#endif
254

255
    } else {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
256

Matteo Quintiliani's avatar
Matteo Quintiliani committed
257 258
	nmxp_log_init(nmxp_log_stdout, nmxp_log_stderr);

259 260 261 262 263
	/* Check consistency of params */
	if(nmxptool_check_params(&params) != 0) {
	    return 1;
	}

264 265
	/* List available channels on server */
	if(params.flag_listchannels) {
266

267 268 269 270
	    meta_channelList = nmxp_getMetaChannelList(params.hostname, params.portnumberdap, NMXP_DATA_TIMESERIES, params.flag_request_channelinfo, params.datas_username, params.datas_password, &channelList, nmxptool_sigcondition_read);

	    /* nmxp_meta_chan_print(meta_channelList); */
	    nmxp_meta_chan_print_with_match(meta_channelList, params.channels);
271

272
	    return 1;
273

274 275
	} else if(params.flag_listchannelsnaqs) {

276
	    channelList = nmxp_getAvailableChannelList(params.hostname, params.portnumberpds, NMXP_DATA_TIMESERIES, nmxptool_sigcondition_read);
277 278

	    /* nmxp_chan_print_channelList(channelList); */
279
	    nmxp_chan_print_channelList_with_match(channelList, params.channels, 1);
280

281
	    return 1;
282

283 284
	}
    }
285

286
    nmxp_log(NMXP_LOG_SET, params.verbose_level);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
287 288 289
    if(params.verbose_level != DEFAULT_VERBOSE_LEVEL) {
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_ANY, "verbose_level %d\n", params.verbose_level);
    }
290

291
#ifdef HAVE_LIBMSEED
292
    data_seed.err_general = 0;
293
    if(params.type_writeseed) {
294
	ms_loginit((void*)&nmxptool_log_miniseed, NULL, (void*)&nmxptool_logerr_miniseed, "error: ");
295
	/* Init mini-SEED variables */
296 297 298
	nmxp_data_seed_init(&data_seed, params.outdirseed,
		CURRENT_NETWORK,
		(params.type_writeseed == TYPE_WRITESEED_BUD)? NMXP_TYPE_WRITESEED_BUD : NMXP_TYPE_WRITESEED_SDS);
299 300 301
    }
#endif

302 303 304 305
    nmxptool_log_params(&params);

    if(params.stc == -1) {

306
#ifndef HAVE_WINDOWS_H
307 308 309
	if(params.listen_port != DEFAULT_LISTEN_PORT) {
	    p_func_pd[n_func_pd++] = nmxptool_listen_print_seq_no;
	}
310
#endif
311

312 313 314 315 316 317
	if(params.flag_logdata) {
	    p_func_pd[n_func_pd++] = nmxptool_print_seq_no;
	}

#ifdef HAVE_LIBMSEED
	/* Write Mini-SEED record */
318
	if(params.type_writeseed) {
319 320 321 322 323 324 325 326 327 328 329
	    p_func_pd[n_func_pd++] = nmxptool_write_miniseed;
	}
#endif

#ifdef HAVE___SRC_SEEDLINK_PLUGIN_C
	/* Send data to SeedLink Server */
	if(params.flag_slink) {
	    p_func_pd[n_func_pd++] = nmxptool_send_raw_depoch;
	}
#endif

330 331 332 333 334 335 336 337 338
#ifdef HAVE_LIBMSEED
#ifdef HAVE___SRC_SEEDLINK_PLUGIN_C
	/* Send data to SeedLink Server */
	if(params.flag_slinkms) {
	    p_func_pd[n_func_pd++] = nmxptool_msr_send_mseed;
	}
#endif
#endif

339 340 341 342 343 344 345 346 347 348 349 350 351 352
#ifdef HAVE_EARTHWORMOBJS
	if(params.ew_configuration_file) {
	    p_func_pd[n_func_pd++] = nmxptool_ew_nmx2ew;
	}
#endif

    }

#ifdef HAVE_EARTHWORMOBJS
    if(params.ew_configuration_file) {
	nmxptool_ew_attach();
    }
#endif

353

354
    /* Exit only on request */
355
    while(EXIT_CONDITION) {
356

357
    NMXP_MEM_PRINT_PTR(0, 1);
358

359
    /* Get list of available channels and get a subset list of params.channels */
360
    if( DAP_CONDITION(params) ) {
361
	if_dap_condition_only_one_time = 1;
362
	/* From DataServer */
363
	if(!nmxp_getMetaChannelList(params.hostname, params.portnumberdap, NMXP_DATA_TIMESERIES,
364
		    params.flag_request_channelinfo, params.datas_username, params.datas_password, &channelList, nmxptool_sigcondition_read)) {
365 366
	    return -1;
	}
367 368
    } else {
	/* From NaqsServer */
369
	channelList = nmxp_getAvailableChannelList(params.hostname, params.portnumberpds, NMXP_DATA_TIMESERIES, nmxptool_sigcondition_read);
370 371
    }

372 373 374 375 376
    if(!channelList) {
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CHANNEL, "Channel list has not been received!\n");
	return 1;
    }

377
    channelList_subset = nmxp_chan_subset(channelList, NMXP_DATA_TIMESERIES, params.channels, CURRENT_NETWORK, CURRENT_LOCATION);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
378 379 380
    
    /* Free the complete channel list */
    if(channelList) {
381
	NMXP_MEM_FREE(channelList);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
382 383
	channelList = NULL;
    }
384 385 386

    /* Check if some channel already exists */
    if(channelList_subset->number <= 0) {
387
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CHANNEL, "Channels not found!\n");
388
	return 1;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
389
    } else {
390
	nmxp_chan_print_netchannelList(channelList_subset);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
391

392
	nmxptool_chanseq_init(&channelList_Seq, channelList_subset->number, DEFAULT_BUFFERED_TIME, params.max_tolerable_latency, params.timeoutrecv);
393

Matteo Quintiliani's avatar
Matteo Quintiliani committed
394
#ifdef HAVE_LIBMSEED
395
	if(params.type_writeseed  ||  params.flag_slinkms) {
396
	    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "Init mini-SEED record list.\n");
397

398 399
	    /* Init mini-SEED record list */
	    for(i_chan = 0; i_chan < channelList_subset->number; i_chan++) {
400

401 402
		nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA,
			"Init mini-SEED record for %s\n", NMXP_LOG_STR(channelList_subset->channel[i_chan].name));
403

404
		msr_list_chan[i_chan] = msr_init(NULL);
405

406
		/* Separate station_code and channel_code */
407
		if(nmxp_chan_cpy_sta_chan(channelList_subset->channel[i_chan].name, station_code, channel_code, network_code, location_code)) {
408

409 410
		    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "%s.%s.%s\n",
			    NMXP_LOG_STR(NETCODE_OR_CURRENT_NETWORK), NMXP_LOG_STR(station_code), NMXP_LOG_STR(channel_code));
411 412 413
		    strncpy(msr_list_chan[i_chan]->network, NETCODE_OR_CURRENT_NETWORK, 11);
		    strncpy(msr_list_chan[i_chan]->station, station_code, 11);
		    strncpy(msr_list_chan[i_chan]->channel, channel_code, 11);
414 415 416 417 418
		    if(location_code[0] != 0) {
		      if(strcmp(location_code, DEFAULT_NULL_LOCATION) != 0) {
			strncpy(msr_list_chan[i_chan]->location, location_code, 11);
		      }
		    }
419

Matteo Quintiliani's avatar
Matteo Quintiliani committed
420
		    msr_list_chan[i_chan]->reclen   = params.reclen;     /* Byte record length */
421
		    msr_list_chan[i_chan]->encoding = params.encoding;  /* Steim 1 compression by default */
422

Matteo Quintiliani's avatar
Matteo Quintiliani committed
423 424 425 426 427
		    /* Reset some values */
		    msr_list_chan[i_chan]->sequence_number = 0;
		    msr_list_chan[i_chan]->datasamples = NULL;
		    msr_list_chan[i_chan]->numsamples = 0;

428 429 430 431 432
		} else {
		    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CHANNEL,
			    "Channels %s error in format!\n", NMXP_LOG_STR(channelList_subset->channel[i_chan].name));
		    return 1;
		}
433

434
	    }
Matteo Quintiliani's avatar
Matteo Quintiliani committed
435 436
	}
#endif
437

438 439
    }

Matteo Quintiliani's avatar
Matteo Quintiliani committed
440
    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "Begin communication.\n");
Matteo Quintiliani's avatar
Matteo Quintiliani committed
441

442
    times_flow = 0;
443
    recv_errno = 0;
444

445 446 447 448 449
    while(times_flow < 2  &&  recv_errno == 0 && !nmxptool_sigcondition_read()
#ifdef HAVE_LIBMSEED
	    &&  data_seed.err_general==0
#endif
	    ) {
450

451
	if(params.statefile) {
452
	    nmxptool_chanseq_load_states(channelList_subset, channelList_Seq, params.statefile, params.stc);
453 454
	}

455 456 457 458 459 460 461 462 463 464 465
	if(times_flow == 0) {
	    if(params.statefile) {
		params.interval = DEFAULT_INTERVAL_INFINITE;
	    }
	} else if(times_flow == 1) {
	    params.start_time = 0.0;
	    params.end_time = 0.0;
	    params.interval = DEFAULT_INTERVAL_NO_VALUE;

	}

Matteo Quintiliani's avatar
Matteo Quintiliani committed
466
    /* Condition for starting DAP or PDS */
467 468
    if( DAP_CONDITION(params) ||
	    (times_flow == 0  &&  params.statefile && params.max_data_to_retrieve > 0 && params.interval == DEFAULT_INTERVAL_INFINITE) ) {
469 470

	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "Begin DAP Flow.\n");
471

472 473 474 475 476 477 478
	if(params.interval > 0  ||  params.interval == DEFAULT_INTERVAL_INFINITE) {
	    if(params.interval > 0) {
		params.end_time = params.start_time + params.interval;
	    } else {
		params.end_time = nmxp_data_gmtime_now();
	    }
	} else if(params.delay > 0) {
479 480
	    params.start_time = ((double) (time(NULL) - params.delay - params.span_data) / 10.0) * 10.0;
	    params.end_time = params.start_time + params.span_data;
481 482
	}

483

484 485 486
	/* ************************************************************** */
	/* Start subscription protocol "DATA ACCESS PROTOCOL" version 1.0 */
	/* ************************************************************** */
487

488
	/* DAP Step 1: Open a socket */
489
	if( (naqssock = nmxp_openSocket(params.hostname, params.portnumberdap, nmxptool_sigcondition_read)) == NMXP_SOCKET_ERROR) {
490
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error opening socket!\n");
491 492
	    return 1;
	}
493

494 495
	/* DAP Step 2: Read connection time */
	if(nmxp_readConnectionTime(naqssock, &connection_time) != NMXP_SOCKET_OK) {
496
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error reading connection time from server!\n");
497 498
	    return 1;
	}
499

500 501
	/* DAP Step 3: Send a ConnectRequest */
	if(nmxp_sendConnectRequest(naqssock, params.datas_username, params.datas_password, connection_time) != NMXP_SOCKET_OK) {
502
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error sending connect request!\n");
503 504 505 506 507
	    return 1;
	}

	/* DAP Step 4: Wait for a Ready message */
	if(nmxp_waitReady(naqssock) != NMXP_SOCKET_OK) {
508
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error waiting Ready message!\n");
509 510
	    return 1;
	}
511

512 513
	exitdapcondition = 1;

514
	default_start_time = (params.start_time > 0.0)? params.start_time : nmxp_data_gmtime_now() - params.max_data_to_retrieve;
515

516 517 518 519 520
	while(exitdapcondition  &&  !nmxptool_sigcondition_read()
#ifdef HAVE_LIBMSEED
		&&  data_seed.err_general==0
#endif
	     ) {
521

522
	    /* Start loop for sending requests */
523
	    request_chan=0;
524
	    request_SOCKET_OK = NMXP_SOCKET_OK;
525

526
	    /* For each channel */
527 528 529 530 531
	    while(request_SOCKET_OK == NMXP_SOCKET_OK  &&  request_chan < channelList_subset->number  &&  exitdapcondition && !nmxptool_sigcondition_read()
#ifdef HAVE_LIBMSEED
		    &&  data_seed.err_general==0
#endif
		    ) {
532

533
		if(params.statefile) {
534 535
		    if(channelList_Seq[request_chan].after_start_time > 0) {
			params.start_time = channelList_Seq[request_chan].after_start_time;
536
			if(params.end_time - params.start_time > params.max_data_to_retrieve) {
537
			    nmxp_data_to_str(start_time_str, params.start_time);
538
			    nmxp_data_to_str(default_start_time_str, params.end_time - params.max_data_to_retrieve);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
539
			    nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_ANY, "%s start_time changed from %s to %s\n",
540 541 542
				    NMXP_LOG_STR(channelList_subset->channel[request_chan].name),
				    NMXP_LOG_STR(start_time_str),
				    NMXP_LOG_STR(default_start_time_str));
543
			    params.start_time = params.end_time - params.max_data_to_retrieve;
544
			}
545 546 547
		    } else {
			params.start_time = default_start_time;
		    }
548 549
		    channelList_Seq[request_chan].last_time = params.start_time;
		    channelList_Seq[request_chan].significant = 1;
550

551
		}
552

553 554
		nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "nmxp_sendDataRequest %d %s (%d)\n",
			channelList_subset->channel[request_chan].key,
555 556
			NMXP_LOG_STR(channelList_subset->channel[request_chan].name),
			request_chan);
557

558 559 560
		nmxp_data_to_str(start_time_str, params.start_time);
		nmxp_data_to_str(end_time_str, params.end_time);
		nmxp_data_to_str(default_start_time_str, default_start_time);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
561
		nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "%s start_time = %s - end_time = %s - (default_start_time = %s)\n",
562 563 564 565
			NMXP_LOG_STR(channelList_subset->channel[request_chan].name),
			NMXP_LOG_STR(start_time_str),
			NMXP_LOG_STR(end_time_str),
			NMXP_LOG_STR(default_start_time_str));
566

567
		/* DAP Step 5: Send Data Request */
568
		request_SOCKET_OK = nmxp_sendDataRequest(naqssock, channelList_subset->channel[request_chan].key, (int32_t) params.start_time, (int32_t) (params.end_time + 1.0));
569

570
		if(request_SOCKET_OK == NMXP_SOCKET_OK) {
571

572 573 574 575
		    nmxp_data_to_str(str_start_time, params.start_time);
		    nmxp_data_to_str(str_end_time, params.end_time);
		    nmxptool_str_time_to_filename(str_start_time);
		    nmxptool_str_time_to_filename(str_end_time);
576
/*Possible bug params not inited*/
577 578
		    if(params.flag_writefile) {
			/* Open output file */
579
			if(nmxp_chan_cpy_sta_chan(channelList_subset->channel[request_chan].name, station_code, channel_code, network_code, location_code)) {
580 581 582 583 584 585 586 587
			    sprintf(filename, "%s.%s.%s_%s_%s.nmx",
				    NETCODE_OR_CURRENT_NETWORK,
				    station_code,
				    channel_code,
				    str_start_time,
				    str_end_time);
			} else {
			    sprintf(filename, "%s_%s_%s.nmx",
588
				    channelList_subset->channel[request_chan].name,
589 590 591
				    str_start_time,
				    str_end_time);
			}
592

593 594
			outfile = fopen(filename, "w");
			if(!outfile) {
595
			    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_EXTRA, "Can not open file %s!\n",
596
				    NMXP_LOG_STR(filename));
597
			}
598
		    }
599

600 601 602 603
		    if(params.flag_writefile  &&  outfile) {
			/* Compute SNCL line */

			/* Separate station_code_old_way and channel_code_old_way */
604
			if(nmxp_chan_cpy_sta_chan(channelList_subset->channel[request_chan].name, station_code, channel_code, network_code, location_code)) {
605 606 607 608 609 610 611
			    /* Write SNCL line */
			    fprintf(outfile, "%s.%s.%s.%s\n",
				    station_code,
				    NETCODE_OR_CURRENT_NETWORK,
				    channel_code,
				    (params.location)? params.location : "");
			}
612

613
		    }
614

615
		    /* DAP Step 6: Receive Data until receiving a Ready message */
616
		    ret = nmxp_receiveMessage(naqssock, &type, buffer, &length, 0, &recv_errno, NMXP_MAX_LENGTH_DATA_BUFFER);
617

618 619
		    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "ret = %d, type = %d, length = %d, recv_errno = %d\n",
			    ret, type, length, recv_errno);
620

621 622 623 624 625
		    while(ret == NMXP_SOCKET_OK   &&    type != NMXP_MSG_READY  && !nmxptool_sigcondition_read()
#ifdef HAVE_LIBMSEED
			    &&  data_seed.err_general==0
#endif
			 ) {
626 627 628 629 630 631 632 633 634
			/* Process a packet and return value in NMXP_DATA_PROCESS structure */ /*STEFANO*/
                        
			if (pd != NULL) {
			    if (pd->pDataPtr != NULL) {
				NMXP_MEM_FREE(pd->pDataPtr);
			    }
			    NMXP_MEM_FREE(pd);
			}

635
			pd = nmxp_processCompressedData(buffer, length, channelList_subset, NETCODE_OR_CURRENT_NETWORK, LOCCODE_OR_CURRENT_LOCATION);
636 637 638 639 640 641

			/* Force value for timing_quality if declared in the command-line */
			if(pd && params.timing_quality != -1) {
			    pd->timing_quality = params.timing_quality;
			}

642 643 644 645 646 647
                        /* set the data quality indicator */			
			if (pd) {
                          pd->quality_indicator = params.quality_indicator;
                        }
			                                                                          

648
			nmxp_data_trim(pd, params.start_time, params.end_time, 0);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
649

650 651 652
			/* To prevent to manage a packet with zero sample after nmxp_data_trim() */
			if(pd->nSamp > 0) {

653 654
			/* Log contents of last packet */
			if(params.flag_logdata) {
655
			    nmxp_data_log(pd, params.flag_logsample);
656
			}
657

658 659
			/* Set cur_chan */
			cur_chan = nmxp_chan_lookupKeyIndex(pd->key, channelList_subset);
660 661 662 663 664

			/* It is not the channel I have requested or error from nmxp_chan_lookupKeyIndex() */
			if(request_chan != cur_chan  &&  cur_chan != -1) {
			    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_ANY, "request_chan != cur_chan  %d != %d! (%d, %s) (%d, %s.%s.%s)\n",
				    request_chan, cur_chan,
665 666 667
				    channelList_subset->channel[request_chan].key,
				    NMXP_LOG_STR(channelList_subset->channel[request_chan].name),
				    pd->key, NMXP_LOG_STR(pd->network), NMXP_LOG_STR(pd->station), NMXP_LOG_STR(pd->channel));
668
			} else {
669

670
			/* Management of gaps */
671
			nmxptool_chanseq_gap(&(channelList_Seq[cur_chan]), pd);
672

673
#ifdef HAVE_LIBMSEED
674
			/* Write Mini-SEED record */
675
			if(params.type_writeseed) {
676 677
			    nmxptool_write_miniseed(pd);
			}
678
#endif
679

680
#ifdef HAVE___SRC_SEEDLINK_PLUGIN_C
681 682 683 684
			/* Send data to SeedLink Server */
			if(params.flag_slink) {
			    nmxptool_send_raw_depoch(pd);
			}
685 686
#endif

687 688 689 690 691 692 693 694 695
#ifdef HAVE_LIBMSEED
#ifdef HAVE___SRC_SEEDLINK_PLUGIN_C
			/* Send data to SeedLink Server */
			if(params.flag_slinkms) {
			    nmxptool_msr_send_mseed(pd);
			}
#endif
#endif

696 697 698 699 700 701
#ifdef HAVE_EARTHWORMOBJS
			if(params.ew_configuration_file) {
			    nmxptool_ew_nmx2ew(pd);
			}
#endif

702 703
			if(params.flag_writefile  &&  outfile) {
			    /* Write buffer to the output file */
704
			    if(outfile && length > 0) {
705 706 707 708 709
				int32_t length_int = length;
				nmxp_data_swap_4b((int32_t *) &length_int);
				fwrite(&length_int, sizeof(length_int), 1, outfile);
				fwrite(buffer, length, 1, outfile);
			    }
710
			}
711

712 713 714
			/* Store x_1 */
			channelList_Seq[cur_chan].x_1 = pd->pDataPtr[pd->nSamp-1];

715 716
			}

717 718
			} else {
			    /* TODO: nSamp <= 0 */
719
			}
720

721

722
			/* Receive Data */
723
			ret = nmxp_receiveMessage(naqssock, &type, buffer, &length, 0, &recv_errno, NMXP_MAX_LENGTH_DATA_BUFFER);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
724
			/* nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "ret = %d, type = %d\n", ret, type); */
725
		    }
726

727 728 729 730 731
		    if(params.flag_writefile  &&  outfile) {
			/* Close output file */
			fclose(outfile);
			outfile = NULL;
		    }
732

733 734
		} else {
		    /* TODO: error message */
735
		}
736
		request_chan++;
737 738 739 740 741

#ifdef HAVE_EARTHWORMOBJS
		if(params.ew_configuration_file) {

		    /* Check if we are being asked to terminate */
742
		    if( (ew_check_flag_terminate = nmxptool_ew_check_flag_terminate()) ) {
743
			logit ("t", "nmxptool terminating on request\n");
744
			nmxptool_ew_send_error(NMXPTOOL_EW_ERR_TERMREQ, NULL, params.hostname);
745 746 747 748 749 750 751 752 753 754
			exitdapcondition = 0;
			times_flow = TIMES_FLOW_EXIT;
		    }

		    /* Check if we need to send heartbeat message */
		    nmxptool_ew_send_heartbeat_if_needed();

		}
#endif

755
	    }
756
	    /* DAP Step 7: Repeat steps 5 and 6 for each data request */
757

758
	    if(params.delay > 0) {
759 760
		time_to_sleep = (params.end_time - params.start_time) - (time(NULL) - (params.start_time + params.delay + params.span_data));
		/* TODO if time_to_sleep exceds DAP protocol time-out, split sleep() and send alive packet */
761
		if(time_to_sleep >= 0) {
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
		    while(time_to_sleep>0 && !nmxptool_sigcondition_read()) {
			nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "time to sleep %d sec.\n", time_to_sleep);
			if(time_to_sleep >= NMXP_DAP_TIMEOUT_KEEPALIVE) {
			    nmxp_sleep(NMXP_DAP_TIMEOUT_KEEPALIVE);
			    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "nmxp_sendRequestPending\n");
			    nmxp_sendRequestPending(naqssock);
			    if(nmxp_waitReady(naqssock) != NMXP_SOCKET_OK) {
				nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error waiting Ready message!\n");
				return 1;
			    }
			} else {
			    nmxp_sleep(time_to_sleep);
			}
			time_to_sleep -= NMXP_DAP_TIMEOUT_KEEPALIVE;
		    }
777 778 779 780 781
		} else {
		    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "time to sleep %d sec.\n", time_to_sleep);
		    nmxp_sleep(3);
		}
		params.start_time = params.end_time;
782
		params.end_time = params.start_time + params.span_data;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
783
	    } else {
784
		exitdapcondition = 0;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
785
	    }
786

787
	} /* END while(exitdapcondition) */
788

789 790
#ifdef HAVE_LIBMSEED
	if(params.type_writeseed) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
791 792 793 794 795 796 797 798
	    if(*msr_list_chan) {
		for(i_chan = 0; i_chan < channelList_subset->number; i_chan++) {
		    if(msr_list_chan[i_chan]) {
			/* Flush remaining samples */
			nmxp_data_msr_pack(NULL, &data_seed, msr_list_chan[i_chan]);
		    }
		}
	    }
799 800 801 802
	    nmxp_data_seed_fclose_all(&data_seed);
	}
#endif

803 804 805 806 807
	/* DAP Step 8: Send a Terminate message (optional) */
	nmxp_sendTerminateSubscription(naqssock, NMXP_SHUTDOWN_NORMAL, "Bye!");

	/* DAP Step 9: Close the socket */
	nmxp_closeSocket(naqssock);
808
	naqssock = 0;
809 810 811 812 813

	/* ************************************************************ */
	/* End subscription protocol "DATA ACCESS PROTOCOL" version 1.0 */
	/* ************************************************************ */

814
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "End DAP Flow.\n");
815

Matteo Quintiliani's avatar
Matteo Quintiliani committed
816
    } else {
817

818 819
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "Begin PDS Flow.\n");

820 821 822 823 824
	/* ************************************************************* */
	/* Start subscription protocol "PRIVATE DATA STREAM" version 1.4 */
	/* ************************************************************* */

	/* PDS Step 1: Open a socket */
825
	naqssock = nmxp_openSocket(params.hostname, params.portnumberpds, nmxptool_sigcondition_read);
826 827 828

	if(naqssock == NMXP_SOCKET_ERROR) {
	    return 1;
829 830
	}

831 832 833 834 835 836 837 838 839 840 841
	/* PDS Step 2: Send a Connect */
	if(nmxp_sendConnect(naqssock) != NMXP_SOCKET_OK) {
	    printf("Error on sendConnect()\n");
	    return 1;
	}

	/* PDS Step 3: Receive ChannelList */
	if(nmxp_receiveChannelList(naqssock, &channelList) != NMXP_SOCKET_OK) {
	    printf("Error on receiveChannelList()\n");
	    return 1;
	}
842
	/* Get a subset of channel from arguments, in respect to the step 3 of PDS */
843
	channelList_subset_waste = nmxp_chan_subset(channelList, NMXP_DATA_TIMESERIES, params.channels, CURRENT_NETWORK, CURRENT_LOCATION);
844

Matteo Quintiliani's avatar
Matteo Quintiliani committed
845 846
	/* Free the complete channel list */
	if(channelList) {
847
	    NMXP_MEM_FREE(channelList);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
848 849 850
	    channelList = NULL;
	}

851 852
	/* TODO check if channelList_subset_waste is equal to channelList_subset and free */
	if(channelList_subset_waste) {
853
	    NMXP_MEM_FREE(channelList_subset_waste);
854 855
	    channelList_subset_waste = NULL;
	}
856

857 858 859 860 861 862 863 864 865 866
	/* PDS Step 4: Send a Request Pending (optional) */

	/* PDS Step 5: Send AddChannels */
	/* Request Data */

	/* Better using a Thread */
#ifndef HAVE_PTHREAD_H
	nmxp_sendAddTimeSeriesChannel(naqssock, channelList_subset, params.stc, params.rate,
		(params.flag_buffered)? NMXP_BUFFER_YES : NMXP_BUFFER_NO, params.n_channel, params.usec, 1);
#else
867
	pthread_attr_init(&attr_request_channels);
868
	pthread_attr_setdetachstate(&attr_request_channels, PTHREAD_CREATE_DETACHED);
869 870
	pthread_create(&thread_request_channels, &attr_request_channels, p_nmxp_sendAddTimeSeriesChannel, (void *)NULL);
	pthread_attr_destroy(&attr_request_channels);
871 872
#endif

873
#ifndef HAVE_WINDOWS_H
874
#ifdef HAVE_PTHREAD_H
875 876
	if(!already_listen  &&  params.listen_port != DEFAULT_LISTEN_PORT) {
	    already_listen = 1;
877 878
	    pthread_attr_init(&attr_socket_listen);
	    pthread_attr_setdetachstate(&attr_socket_listen, PTHREAD_CREATE_DETACHED);
879
	    pthread_create(&thread_socket_listen, &attr_socket_listen, nmxptool_listen, (void *) &params.listen_port);
880 881
	    pthread_attr_destroy(&attr_socket_listen);
	}
882
#endif
883 884
#endif

885
	/* PDS Step 6: Repeat until finished: receive and handle packets */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
886

887
	/* TODO*/
Matteo Quintiliani's avatar
Matteo Quintiliani committed
888
	exitpdscondition = 1;
889
	flag_force_close_connection = 0;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
890

891
	skip_current_packet = 0;
892
	/* begin  main PDS loop */
893

894
	while(exitpdscondition && !nmxptool_sigcondition_read() && !flag_force_close_connection
895 896 897 898
#ifdef HAVE_LIBMSEED
		&&  data_seed.err_general==0
#endif
	     ) {
899 900 901 902 903 904 905 906
	    
	    /* added 2010-07-26, RR */
            if (pd != NULL) {
              if (pd->pDataPtr != NULL) {
                NMXP_MEM_FREE(pd->pDataPtr);
              }
              NMXP_MEM_FREE(pd);
            } 
907
	    /* Process Compressed or Decompressed Data */
908
	    pd = nmxp_receiveData(naqssock, channelList_subset, NETCODE_OR_CURRENT_NETWORK, LOCCODE_OR_CURRENT_LOCATION, params.timeoutrecv, &recv_errno);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
909

910 911 912
            
            

913 914 915 916
	    /* Force value for timing_quality if declared in the command-line */
	    if(pd && params.timing_quality != -1) {
		pd->timing_quality = params.timing_quality;
	    }
917 918 919 920 921 922
            
            /* set the data quality indicator */
            if (pd) {
              pd->quality_indicator = params.quality_indicator;
            }
                                                                                                            
923 924 925 926 927 928 929 930 931 932 933
	    if(!pd) {
		pd_null_count++;
		if((pd_null_count * params.timeoutrecv) >= timeoutrecv_warning) {
		    nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_ANY, "Received %d times a null packet. (%d sec.)\n",
			    pd_null_count, pd_null_count * params.timeoutrecv);
		    pd_null_count = 0;
		}
	    } else {
		pd_null_count = 0;
	    }

934
	    if(recv_errno == 0) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
935 936
		exitpdscondition = 1;
	    } else {
937 938 939 940 941 942
#ifdef HAVE_WINDOWS_H
		if(recv_errno == WSAEWOULDBLOCK  ||  recv_errno == WSAETIMEDOUT)
#else
		if(recv_errno == EWOULDBLOCK)
#endif
		{
943 944
		    exitpdscondition = 1;
		} else {
945 946
		    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error receiving data. pd=%p recv_errno=%d\n",
			    pd, recv_errno);
947 948

#ifdef HAVE_EARTHWORMOBJS
949
		    if(params.ew_configuration_file) {
950 951
                        recv_errno_str=nmxp_strerror(recv_errno);