nmxp.c 34.3 KB
Newer Older
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
1
2
/*! \file
 *
Matteo Quintiliani's avatar
Matteo Quintiliani committed
3
 * \brief Nanometrics Protocol Library
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
4
5
6
7
8
9
 *
 * Author:
 * 	Matteo Quintiliani
 * 	Istituto Nazionale di Geofisica e Vulcanologia - Italy
 *	quintiliani@ingv.it
 *
10
 * $Id: nmxp.c,v 1.86 2008-04-05 14:08:00 mtheo Exp $
Matteo Quintiliani's avatar
Matteo Quintiliani committed
11
 *
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
12
13
14
 */

#include "nmxp.h"
15
#include "nmxp_memory.h"
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
16

Matteo Quintiliani's avatar
Matteo Quintiliani committed
17
18
#include "config.h"

Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
19
#include <stdio.h>
20
#include <stdlib.h>
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
21
22
#include <string.h>

23
24
25
26
#ifdef HAVE_GETTIMEOFDAY
#include <sys/time.h>
#endif

Matteo Quintiliani's avatar
Matteo Quintiliani committed
27
28
29
30
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif

31
32
33
34
#ifdef HAVE_WINDOWS_H
#include "winsock2.h"
#endif

35
int nmxp_sendConnect(int isock) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
36
    return nmxp_sendMessage(isock, NMXP_MSG_CONNECT, NULL, 0);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
37
38
}

Matteo Quintiliani's avatar
Matteo Quintiliani committed
39
40
int nmxp_sendTerminateSubscription(int isock, NMXP_SHUTDOWN_REASON reason, char *message) {
    return nmxp_sendMessage(isock, NMXP_MSG_TERMINATESUBSCRIPTION, message, ((message)? strlen(message)-1 : 0));
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
41
42
}

Matteo Quintiliani's avatar
Matteo Quintiliani committed
43
int nmxp_receiveChannelList(int isock, NMXP_CHAN_LIST **pchannelList) {
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
44
45
    int ret;
    int i;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
46
    int recv_errno;
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
47

Matteo Quintiliani's avatar
Matteo Quintiliani committed
48
    NMXP_MSG_SERVER type;
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
49
    void *buffer;
50
    int32_t length;
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
51
52
53

    *pchannelList = NULL;

Matteo Quintiliani's avatar
Matteo Quintiliani committed
54
    ret = nmxp_receiveMessage(isock, &type, &buffer, &length, 0, &recv_errno);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
55

Matteo Quintiliani's avatar
Matteo Quintiliani committed
56
    if(type != NMXP_MSG_CHANNELLIST) {
57
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_PACKETMAN, "Type %d is not NMXP_MSG_CHANNELLIST!\n", type);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
58
59
60
61
62
    } else {

	*pchannelList = buffer;
	(*pchannelList)->number = ntohl((*pchannelList)->number);

63
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CHANNEL, "number of channels %d\n", (*pchannelList)->number);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
64
	
65
	/* TODO check*/
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
66
67
68

	for(i=0; i < (*pchannelList)->number; i++) {
	    (*pchannelList)->channel[i].key = ntohl((*pchannelList)->channel[i].key);
69
70
71
	    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CHANNEL, "%12d %s\n",
		    (*pchannelList)->channel[i].key,
		    NMXP_LOG_STR((*pchannelList)->channel[i].name));
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
72
73
74
75
76
77
78
79
	}

    }

    return ret;
}


80
int nmxp_sendAddTimeSeriesChannel_raw(int isock, NMXP_CHAN_LIST_NET *channelList, int32_t shortTermCompletion, int32_t out_format, NMXP_BUFFER_FLAG buffer_flag) {
81
    int ret;
82
    int32_t buffer_length = 16 + (4 * channelList->number); 
83
    char *buffer = NMXP_MEM_MALLOC(buffer_length);
84
    int32_t app, i, disp;
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

    disp=0;

    app = htonl(channelList->number);
    memcpy(&buffer[disp], &app, 4);
    disp+=4;

    for(i=0; i < channelList->number; i++) {
	app = htonl(channelList->channel[i].key);
	memcpy(&buffer[disp], &app, 4);
	disp+=4;
    }
    
    app = htonl(shortTermCompletion);
    memcpy(&buffer[disp], &app, 4);
    disp+=4;

    app = htonl(out_format);
    memcpy(&buffer[disp], &app, 4);
    disp+=4;

    app = htonl(buffer_flag);
    memcpy(&buffer[disp], &app, 4);
    disp+=4;

Matteo Quintiliani's avatar
Matteo Quintiliani committed
110
    ret = nmxp_sendMessage(isock, NMXP_MSG_ADDTIMESERIESCHANNELS, buffer, buffer_length);
111
112

    if(buffer) {
113
	NMXP_MEM_FREE(buffer);
114
	buffer = NULL;
115
116
117
118
    }
    return ret;
}

119
int nmxp_sendAddTimeSeriesChannel(int isock, NMXP_CHAN_LIST_NET *channelList, int32_t shortTermCompletion, int32_t out_format, NMXP_BUFFER_FLAG buffer_flag, int n_channel, int n_usec, int flag_restart) {
120
121
122
123
    static int i = 0;
    static int first_time = 1;
    static struct timeval last_tp_now;

124
    char s_channels[1024];
125
126
127
128
129
    int j;
    int ret = 0;
    NMXP_CHAN_LIST_NET split_channelList;
    long diff_usec;
    struct timeval tp_now;
130
131
132
133
134
135
136
    double estimated_time = 0.0;

    if(n_usec == 0  &&  n_channel == 0) {
	n_channel = channelList->number;
    }

    estimated_time = (double) channelList->number * ( ((double) n_usec / 1000000.0) / (double) n_channel);
137

138
    if(flag_restart) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
139
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW,
140
141
142
143
144
		"Estimated time for channel requests: %d * (%d/%d) = %.3f sec.\n",
		channelList->number, n_usec / 1000, n_channel,
		estimated_time);


145
146
147
148
	first_time = 1;
	i = 0;
    }

Matteo Quintiliani's avatar
Matteo Quintiliani committed
149
    /* Check if requests could be satisfied within NMXP_MAX_MSCHAN_MSEC */
150
151
152
153
154
155
156
157
158
    if(estimated_time > ((double) NMXP_MAX_MSCHAN_MSEC / 1000.0)) {
	n_usec = ( (double) NMXP_MAX_MSCHAN_MSEC * 1000.0 ) * ( (double) n_channel / (double) channelList->number);
	estimated_time = (double) channelList->number * ( ((double) n_usec / 1000000.0) / (double) n_channel);
	if(flag_restart) {
	    nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_ANY, "Estimated time exceeds. New values %d/%d and estimated time %.3f sec.\n",
		    n_usec/1000, n_channel, estimated_time);
	}
    }

159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#ifdef HAVE_GETTIMEOFDAY
    gettimeofday(&tp_now, NULL);
#else
    TODO gettimeofday not found
#endif

    if(i <  channelList->number) {
	    if(first_time) {
		    diff_usec = n_usec + 1;
		    first_time = 0;
		    last_tp_now.tv_sec = 0;
		    last_tp_now.tv_usec = 0;
	    } else {
		    diff_usec = (tp_now.tv_sec - last_tp_now.tv_sec) * 1000000;
		    diff_usec += (tp_now.tv_usec - last_tp_now.tv_usec);
	    }
	    if(diff_usec >= n_usec) {
		    /* while(ret == 0  &&  i <  channelList->number) { */
		    split_channelList.number = 0;
		    while(split_channelList.number < n_channel  &&  i < channelList->number) {
			    split_channelList.channel[split_channelList.number].key = channelList->channel[i].key;
			    /* Not necessary, but it could help for debugging */
			    strcpy(split_channelList.channel[split_channelList.number].name, channelList->channel[i].name);
			    split_channelList.number++;
			    i++;
		    }
		    if(split_channelList.number > 0) {
186
187
			snprintf(s_channels, 1024, "%.0f/%d chan %d of %d:",
				(double)diff_usec/1000.0, split_channelList.number, i, channelList->number);
188
			    for(j=0; j < split_channelList.number; j++) {
189
190
				strncat(s_channels," ", 1024);
				strncat(s_channels, NMXP_LOG_STR(split_channelList.channel[j].name), 1024);
191
			    }
192
			    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "%s\n", s_channels);
193
194
195
196
197
198
199
200
201
202
203
			    ret = nmxp_sendAddTimeSeriesChannel_raw(isock, &split_channelList, shortTermCompletion, out_format, buffer_flag);
		    }
		    /* } */
		    last_tp_now.tv_sec = tp_now.tv_sec;
		    last_tp_now.tv_usec = tp_now.tv_usec;
	    }
    }

    return ret;
}

204

Matteo Quintiliani's avatar
Matteo Quintiliani committed
205
NMXP_DATA_PROCESS *nmxp_receiveData(int isock, NMXP_CHAN_LIST_NET *channelList, const char *network_code, int timeoutsec, int *recv_errno ) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
206
    NMXP_MSG_SERVER type;
207
    void *buffer = NULL;
208
    int32_t length;
209
    NMXP_DATA_PROCESS *pd = NULL;
210

Matteo Quintiliani's avatar
Matteo Quintiliani committed
211
    if(nmxp_receiveMessage(isock, &type, &buffer, &length, timeoutsec, recv_errno) == NMXP_SOCKET_OK) {
212
	if(type == NMXP_MSG_COMPRESSED) {
213
	    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_PACKETMAN, "Type %d is NMXP_MSG_COMPRESSED!\n", type);
214
	    pd = nmxp_processCompressedData(buffer, length, channelList, network_code);
215
	} else if(type == NMXP_MSG_DECOMPRESSED) {
216
	    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_PACKETMAN, "Type %d is NMXP_MSG_DECOMPRESSED!\n", type);
217
	    pd = nmxp_processDecompressedData(buffer, length, channelList, network_code);
218
	} else {
219
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_PACKETMAN, "Type %d is not NMXP_MSG_COMPRESSED or NMXP_MSG_DECOMPRESSED!\n", type);
220
	}
Matteo Quintiliani's avatar
Matteo Quintiliani committed
221
222
    }

223
    return pd;
224
225
}

226

227
int nmxp_sendConnectRequest(int isock, char *naqs_username, char *naqs_password, int32_t connection_time) {
228
    int ret;
229
    int i;
230
    char crc32buf[100];
231
232
    char *pcrc32buf = crc32buf;
    int crc32buf_length = 0;
233
    NMXP_CONNECT_REQUEST connectRequest;
234
    int naqs_username_length, naqs_password_length;
235
    int32_t protocol_version = 0;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
236
    char *pp = NULL;
237

238
239
    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CRC, "%s - %s\n",
	    NMXP_LOG_STR(naqs_username), NMXP_LOG_STR(naqs_password));
240

241
242
243
    naqs_username_length = (naqs_username)? strlen(naqs_username) : 0;
    naqs_password_length = (naqs_password)? strlen(naqs_password) : 0;

244
245
246
247
248
249
250
251
    for(i=0; i < 100; i++) {
	crc32buf[i] = 0;
    }

    for(i=0; i<12; i++) {
	connectRequest.username[i] = 0;
    }
    if(naqs_username_length != 0) {
252
	strcpy(connectRequest.username, naqs_username);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
253
    }
254
255
256
257

    connectRequest.version = protocol_version;
    connectRequest.connection_time = connection_time;

258
259
260
    if(!nmxp_data_bigendianhost()) {
	nmxp_data_swap_4b ((int32_t *)&connection_time);
    }
261

262
    if(naqs_username_length == 0  &&  naqs_password_length == 0 ) {
263
264
	/* sprintf(crc32buf, "%d%d", protocol_version, connection_time); */
	/* TODO */
265
    } else if(naqs_username_length != 0  &&  naqs_password_length != 0 ) {
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
	/* sprintf(crc32buf, "%s%d%d%s", naqs_username, protocol_version,
		connection_time, naqs_password); */

	memcpy(pcrc32buf, naqs_username, naqs_username_length);
	crc32buf_length += naqs_username_length;
	pcrc32buf = crc32buf + crc32buf_length;

	memcpy(pcrc32buf, &(protocol_version), sizeof(protocol_version));
	crc32buf_length += sizeof(protocol_version);
	pcrc32buf = crc32buf + crc32buf_length;

	memcpy(pcrc32buf, &(connection_time), sizeof(connection_time));
	crc32buf_length += sizeof(connection_time);
	pcrc32buf = crc32buf + crc32buf_length;

	memcpy(pcrc32buf, naqs_password, naqs_password_length);
	crc32buf_length += naqs_password_length;
	pcrc32buf = crc32buf + crc32buf_length;

285
    } else if(naqs_username_length != 0 ) {
286
287
	/* sprintf(crc32buf, "%s%d%d", naqs_username, protocol_version, connection_time); */
	/* TODO */
288
    } else if(naqs_password_length != 0 ) {
289
290
	/* sprintf(crc32buf, "%d%d%s", protocol_version, connection_time, naqs_password); */
	/* TODO */
291
    }
292
293
294
    connectRequest.version = htonl(connectRequest.version);
    connectRequest.connection_time = htonl(connectRequest.connection_time);
    connectRequest.crc32 = htonl(crc32(0L, crc32buf, crc32buf_length));
295
296
297
298

    ret = nmxp_sendMessage(isock, NMXP_MSG_CONNECTREQUEST, &connectRequest, sizeof(NMXP_CONNECT_REQUEST));

    if(ret == NMXP_SOCKET_OK) {
299
300
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CRC, "Send a ConnectRequest crc32buf length %d, crc32 = %d\n",
		crc32buf_length, connectRequest.crc32);
301
302
303
	for(i=0; i < crc32buf_length; i++) {
	    nmxp_log(NMXP_LOG_NORM_NO, NMXP_LOG_D_CRC, "%d ", crc32buf[i]);
	}
Matteo Quintiliani's avatar
Matteo Quintiliani committed
304
	pp = (char *) &connectRequest.crc32;
305
306
307
308
	for(i=0; i < sizeof(connectRequest.crc32); i++) {
	    nmxp_log(NMXP_LOG_NORM_NO, NMXP_LOG_D_CRC, "%d ", pp[i]);
	}
	nmxp_log(NMXP_LOG_NORM_NO, NMXP_LOG_D_CRC, "\n");
309
    } else {
310
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CRC, "Send a ConnectRequest.\n");
311
312
313
314
315
316
    }

    return ret;
}


317
int nmxp_readConnectionTime(int isock, int32_t *connection_time) {
318
    int ret;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
319
320
    int recv_errno;
    ret = nmxp_recv_ctrl(isock, connection_time, sizeof(int32_t), 0, &recv_errno);
321
    *connection_time = ntohl(*connection_time);
322
    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "Read connection time from socket %d.\n", *connection_time);
323
    if(ret != NMXP_SOCKET_OK) {
324
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Read connection time from socket.\n");
325
326
327
328
329
    }
    return ret;
}


330
int nmxp_waitReady(int isock) {
331
332
    int times = 0;
    int rc = NMXP_SOCKET_OK;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
333
334
335
    int32_t signature;
    int32_t type = 0;
    int32_t length;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
336
    int recv_errno;
337
338

    while(rc == NMXP_SOCKET_OK  &&  type != NMXP_MSG_READY) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
339
	rc = nmxp_recv_ctrl(isock, &signature, sizeof(signature), 0, &recv_errno);
340
341
342
	if(rc != NMXP_SOCKET_OK) return rc;
	signature = ntohl(signature);
	if(signature == 0) {
343
	    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "signature is equal to zero. receive again.\n");
Matteo Quintiliani's avatar
Matteo Quintiliani committed
344
	    rc = nmxp_recv_ctrl(isock, &signature, sizeof(signature), 0, &recv_errno);
345
346
347
	    signature = ntohl(signature);
	}
	if(signature != NMX_SIGNATURE) {
348
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "signature is not valid. signature = %d\n", signature);
349
350
351
352
	    if(signature == 200) {
		    int32_t err_length;
		    int32_t err_reason;
		    char err_buff[200];
Matteo Quintiliani's avatar
Matteo Quintiliani committed
353
		    rc = nmxp_recv_ctrl(isock, &err_length, sizeof(err_length), 0, &recv_errno);
354
		    err_length = ntohl(err_length);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
355
		    rc = nmxp_recv_ctrl(isock, &err_reason, sizeof(err_reason), 0, &recv_errno);
356
357
		    err_reason = ntohl(err_reason);
		    if(err_length > 4) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
358
			    rc = nmxp_recv_ctrl(isock, err_buff, err_length-4, 0, &recv_errno);
359
360
			    err_buff[err_length] = 0;
		    }
361
		    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "TerminateMessage from Server: %s (%d).\n",
362
			    NMXP_LOG_STR(err_buff), err_reason);
363
	    }
364
365
366
	    return NMXP_SOCKET_ERROR;
	}

Matteo Quintiliani's avatar
Matteo Quintiliani committed
367
	rc = nmxp_recv_ctrl(isock, &type, sizeof(type), 0, &recv_errno);
368
369
370
	if(rc != NMXP_SOCKET_OK) return rc;
	type = ntohl(type);
	if(type != NMXP_MSG_READY) {
371
	    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "type is not READY. type = %d\n", type);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
372
	    rc = nmxp_recv_ctrl(isock, &length, sizeof(length), 0, &recv_errno);
373
374
375
	    if(rc != NMXP_SOCKET_OK) return rc;
	    length = ntohl(length);
	    if(length > 0) {
376
377
		if(type == NMXP_MSG_TERMINATESUBSCRIPTION) {
		    char *str_msg = NULL;
378
		    char *buf_app = (char *) NMXP_MEM_MALLOC(sizeof(char) * length);
379
380
381
382
383
384
385
386
387
388
		    int32_t reason;
		    memcpy(&reason, buf_app, sizeof(reason));
		    reason = ntohl(reason);
		    str_msg = buf_app + sizeof(reason);
		    rc = nmxp_recv_ctrl(isock, buf_app, length, 0, &recv_errno);
		    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_ANY, "%d %s shutdown: %s\n",
			    reason,
			    (reason == 0)? "Normal" : (reason == 1)? "Error" : (reason == 2)? "Timeout" : "Unknown",
			    str_msg);
		    if(buf_app) {
389
			NMXP_MEM_FREE(buf_app);
390
			buf_app = NULL;
391
		    }
392
393
394
		    /* Close the socket*/
		    nmxp_closeSocket(isock);
		    exit(-1);
395
		} else if(length == 4) {
396
		    int32_t app;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
397
		    rc = nmxp_recv_ctrl(isock, &app, length, 0, &recv_errno);
398
399
		    if(rc != NMXP_SOCKET_OK) return rc;
		    app = ntohl(app);
400
		    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CONNFLOW, "value = %d\n", app);
401
		} else {
402
		    char *buf_app = (char *) NMXP_MEM_MALLOC(sizeof(char) * length);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
403
		    rc = nmxp_recv_ctrl(isock, buf_app, length, 0, &recv_errno);
404
		    if(buf_app) {
405
			NMXP_MEM_FREE(buf_app);
406
			buf_app = NULL;
407
408
409
410
		    }
		}
	    }
	} else {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
411
	    rc = nmxp_recv_ctrl(isock, &length, sizeof(length), 0, &recv_errno);
412
413
414
	    if(rc != NMXP_SOCKET_OK) return rc;
	    length = ntohl(length);
	    if(length != 0) {
415
		nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "length is not equal to zero. length = %d\n", length);
416
417
418
419
420
421
		return NMXP_SOCKET_ERROR;
	    }
	}

	times++;
	if(times > 10) {
422
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "waiting_ready_message. times > 10\n");
423
424
425
426
427
428
429
430
431
	    rc = NMXP_SOCKET_ERROR;
	}

    }

    return rc;
}


432
int nmxp_sendDataRequest(int isock, int32_t key, int32_t start_time, int32_t end_time) {
433
434
435
436
437
438
439
440
441
442
    int ret;
    NMXP_DATA_REQUEST dataRequest;

    dataRequest.chan_key = htonl(key);
    dataRequest.start_time = htonl(start_time);
    dataRequest.end_time = htonl(end_time);

    ret = nmxp_sendMessage(isock, NMXP_MSG_DATAREQUEST, &dataRequest, sizeof(dataRequest));

    if(ret != NMXP_SOCKET_OK) {
443
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Send a Request message\n");
444
445
446
447
448
449
    }

    return ret;
}


450
451
452
NMXP_CHAN_LIST *nmxp_getAvailableChannelList(char * hostname, int portnum, NMXP_DATATYPE datatype) {
    int naqssock;
    NMXP_CHAN_LIST *channelList = NULL, *channelList_subset = NULL;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
453
    /* int i; */
454

455
    /* 1. Open a socket*/
456
457
458
459
    naqssock = nmxp_openSocket(hostname, portnum);

    if(naqssock != NMXP_SOCKET_ERROR) {

460
	/* 2. Send a Connect*/
461
462
	if(nmxp_sendConnect(naqssock) == NMXP_SOCKET_OK) {

463
	    /* 3. Receive ChannelList*/
464
465
466
	     if(nmxp_receiveChannelList(naqssock, &channelList) == NMXP_SOCKET_OK) {

		 channelList_subset = nmxp_chan_getType(channelList, datatype);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
467
		 nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CHANNEL, "%d / %d are DataType channel.\n", channelList_subset->number, channelList->number);
468

469
		 /* nmxp_chan_sortByKey(channelList_subset);*/
470
471
		 nmxp_chan_sortByName(channelList_subset);

Matteo Quintiliani's avatar
Matteo Quintiliani committed
472
		 /*
473
		 for(i=0; i < channelList_subset->number; i++) {
474
475
476
		     nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_CHANNEL, "%12d %s\n",
			     channelList_subset->channel[i].key,
			     NMXP_LOG_STR(channelList_subset->channel[i].name));
477
		 }
Matteo Quintiliani's avatar
Matteo Quintiliani committed
478
		 */
479

480
		 /* 4. Send a Request Pending (optional)*/
481

482
		 /* 5. Send AddChannels*/
483

484
		 /* 6. Repeat until finished: receive and handle packets*/
485

486
		 /* 7. Send Terminate Subscription*/
487
488
489
		 nmxp_sendTerminateSubscription(naqssock, NMXP_SHUTDOWN_NORMAL, "Good Bye!");

	     } else {
490
		 nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CHANNEL, "Error on receiveChannelList()\n");
491
492
	     }
	} else {
493
	    nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CHANNEL, "Error on sendConnect()\n");
494
495
	}

496
	/* 8. Close the socket*/
497
498
499
500
	nmxp_closeSocket(naqssock);
    }

    if(channelList) {
501
	NMXP_MEM_FREE(channelList);
502
	channelList = NULL;
503
504
505
506
507
    }

    return channelList_subset;
}

508

509
NMXP_META_CHAN_LIST *nmxp_getMetaChannelList(char * hostname, int portnum, NMXP_DATATYPE datatype, int flag_request_channelinfo, char *datas_username, char *datas_password, NMXP_CHAN_LIST **pchannelList) {
510
511
    int naqssock;
    NMXP_CHAN_PRECISLIST *precisChannelList = NULL;
512
513
514
515
    NMXP_CHAN_LIST *channelList = NULL;
    NMXP_META_CHAN_LIST *chan_list = NULL;
    NMXP_META_CHAN_LIST *iter = NULL;
    int i = 0;
516
    int32_t connection_time;
517
    int ret_sock;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
518
    int recv_errno;
519
    
520
521
    NMXP_MSG_SERVER type;
    void *buffer = NULL;
522
    int32_t length;
523
524
525
    NMXP_PRECISLISTREQUEST precisListRequestBody;
    NMXP_CHANNELINFOREQUEST channelInfoRequestBody;
    NMXP_CHANNELINFORESPONSE *channelInfo;
526
527
528
529
530
531
532

    char str_start[200], str_end[200];
    str_start[0] = 0;
    str_end[0] = 0;
    
    /* DAP Step 1: Open a socket */
    if( (naqssock = nmxp_openSocket(hostname, portnum)) == NMXP_SOCKET_ERROR) {
533
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error opening socket!\n");
534
535
536
537
538
	return NULL;
    }

    /* DAP Step 2: Read connection time */
    if(nmxp_readConnectionTime(naqssock, &connection_time) != NMXP_SOCKET_OK) {
539
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error reading connection time from server!\n");
540
541
542
543
544
	return NULL;
    }

    /* DAP Step 3: Send a ConnectRequest */
    if(nmxp_sendConnectRequest(naqssock, datas_username, datas_password, connection_time) != NMXP_SOCKET_OK) {
545
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error sending connect request!\n");
546
547
548
549
550
	return NULL;
    }

    /* DAP Step 4: Wait for a Ready message */
    if(nmxp_waitReady(naqssock) != NMXP_SOCKET_OK) {
551
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CONNFLOW, "Error waiting Ready message!\n");
552
553
554
	return NULL;
    }

555
556
557
558
559
560



    /* DAP Step 5: Send Data Request */
    nmxp_sendHeader(naqssock, NMXP_MSG_CHANNELLISTREQUEST, 0);
    /* DAP Step 6: Receive Data until receiving a Ready message */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
561
    ret_sock = nmxp_receiveMessage(naqssock, &type, &buffer, &length, 0, &recv_errno);
562
    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "ret_sock = %d, type = %d, length = %d\n", ret_sock, type, length);
563
564
565
566
567
568
569
570

    while(ret_sock == NMXP_SOCKET_OK   &&    type != NMXP_MSG_READY) {
	channelList = buffer;

	channelList->number = ntohl(channelList->number);

	for(i = 0; i < channelList->number; i++) {
	    channelList->channel[i].key = ntohl(channelList->channel[i].key);
571
	    if(getDataTypeFromKey(channelList->channel[i].key) == datatype) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
572
		nmxp_meta_chan_add(&chan_list, channelList->channel[i].key, channelList->channel[i].name, 0, 0, NULL, NMXP_META_SORT_NAME);
573
	    }
574
575
576
	}

	/* Receive Message */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
577
	ret_sock = nmxp_receiveMessage(naqssock, &type, &buffer, &length, 0, &recv_errno);
578
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "ret_sock = %d, type = %d, length = %d\n", ret_sock, type, length);
579
580
    }

581
    *pchannelList = channelList;
582

583
584
585
586
    /* DAP Step 5: Send Data Request */
    precisListRequestBody.instr_id = htonl(-1);
    precisListRequestBody.datatype = htonl(NMXP_DATA_TIMESERIES);
    precisListRequestBody.type_of_channel = htonl(-1);
587
    nmxp_sendMessage(naqssock, NMXP_MSG_PRECISLISTREQUEST, &precisListRequestBody, sizeof(NMXP_PRECISLISTREQUEST));
588

589
590

    /* DAP Step 6: Receive Data until receiving a Ready message */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
591
    ret_sock = nmxp_receiveMessage(naqssock, &type, &buffer, &length, 0, &recv_errno);
592
    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "ret_sock = %d, type = %d, length = %d\n", ret_sock, type, length);
593
594
595
596
597
598
599
600
601
602
603
604
605

    while(ret_sock == NMXP_SOCKET_OK   &&    type != NMXP_MSG_READY) {
	precisChannelList = buffer;

	precisChannelList->number = ntohl(precisChannelList->number);
	for(i = 0; i < precisChannelList->number; i++) {
	    precisChannelList->channel[i].key = ntohl(precisChannelList->channel[i].key);
	    precisChannelList->channel[i].start_time = ntohl(precisChannelList->channel[i].start_time);
	    precisChannelList->channel[i].end_time = ntohl(precisChannelList->channel[i].end_time);

	    nmxp_data_to_str(str_start, precisChannelList->channel[i].start_time);
	    nmxp_data_to_str(str_end, precisChannelList->channel[i].end_time);

606
	    if(!nmxp_meta_chan_set_times(chan_list, precisChannelList->channel[i].key, precisChannelList->channel[i].start_time, precisChannelList->channel[i].end_time)) {
607
608
609
		nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CHANNEL, "Key %d not found for %s!\n",
			precisChannelList->channel[i].key,
			NMXP_LOG_STR(precisChannelList->channel[i].name));
610
611
612
	    }

	    /*
613
	    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_ANY, "%12d %12s %10d %10d %20s %20s\n",
614
		    precisChannelList->channel[i].key, NMXP_LOG_STR(precisChannelList->channel[i].name),
615
		    precisChannelList->channel[i].start_time, precisChannelList->channel[i].end_time,
616
		    NMXP_LOG_STR(str_start), NMXP_LOG_STR(str_end));
617
		    */
618
619
620
	}

	/* Receive Message */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
621
	ret_sock = nmxp_receiveMessage(naqssock, &type, &buffer, &length, 0, &recv_errno);
622
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "ret_sock = %d, type = %d, length = %d\n", ret_sock, type, length);
623
624
625
    }


626
627
    if(flag_request_channelinfo) {
	for(iter = chan_list; iter != NULL; iter = iter->next) {
628

629
630
631
632
	    if(getChannelNumberFromKey(iter->key) == 0) {
		/* DAP Step 5: Send Data Request */
		channelInfoRequestBody.key = htonl(iter->key);
		channelInfoRequestBody.ignored = htonl(0);
633
		nmxp_sendMessage(naqssock, NMXP_MSG_CHANNELINFOREQUEST, &channelInfoRequestBody, sizeof(NMXP_CHANNELINFOREQUEST));
634

635
		/* DAP Step 6: Receive Data until receiving a Ready message */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
636
		ret_sock = nmxp_receiveMessage(naqssock, &type, &buffer, &length, 0, &recv_errno);
637
		nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "ret_sock = %d, type = %d, length = %d\n", ret_sock, type, length);
638

639
640
641
		while(ret_sock == NMXP_SOCKET_OK   &&    type != NMXP_MSG_READY) {
		    channelInfo = buffer;
		    channelInfo->key = ntohl(channelInfo->key);
642

643
		    if(!nmxp_meta_chan_set_network(chan_list, channelInfo->key, channelInfo->network)) {
644
645
			nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_CHANNEL, "Key %d (%d) not found for %s!\n",
				iter->key, channelInfo->key, NMXP_LOG_STR(iter->name));
646
647
		    }
		    /* Receive Message */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
648
		    ret_sock = nmxp_receiveMessage(naqssock, &type, &buffer, &length, 0, &recv_errno);
649
		    nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_EXTRA, "ret_sock = %d, type = %d, length = %d\n", ret_sock, type, length);
650
651
652
		}
	    }
	}
653
654
655
656
657
658
659
660
661
662
663
664
    }



    /* DAP Step 7: Repeat steps 5 and 6 for each data request */

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

    /* DAP Step 9: Close the socket */
    nmxp_closeSocket(naqssock);

665
    return chan_list;
666
667
}

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683

int nmxp_raw_stream_seq_no_compare(const void *a, const void *b)
{       
    int ret = 0;
    NMXP_DATA_PROCESS **ppa = (NMXP_DATA_PROCESS **) a;
    NMXP_DATA_PROCESS **ppb = (NMXP_DATA_PROCESS **) b;
    NMXP_DATA_PROCESS *pa = *ppa;
    NMXP_DATA_PROCESS *pb = *ppb;

    if(pa && pb) {
	if(pa->seq_no > pb->seq_no) {
	    ret = 1;
	} else if (pa->seq_no < pb->seq_no) {
	    ret = -1;
	}
    } else {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
684
685
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_ANY,
		"nmxp_raw_stream_seq_no_compare() pa %s NULL and pb %s NULL\n", (pa)? "!=" : "=", (pb)? "!=" : "=");
686
687
688
689
690
    }

    return ret;
}

Matteo Quintiliani's avatar
Matteo Quintiliani committed
691
void nmxp_raw_stream_init(NMXP_RAW_STREAM_DATA *raw_stream_buffer, int32_t max_tolerable_latency, int timeoutrecv) {
692
693
694
695
    int j;

    raw_stream_buffer->last_seq_no_sent = -1;
    raw_stream_buffer->last_sample_time = -1.0;
696
    raw_stream_buffer->last_latency = 0.0;
697
    /* TODO 
Matteo Quintiliani's avatar
Matteo Quintiliani committed
698
     * Suppose a packet can contain 1/4 secs of data (that is, minimum packet length is 0.25 secs of data) */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
699
700
    raw_stream_buffer->max_tolerable_latency = max_tolerable_latency;
    raw_stream_buffer->max_pdlist_items = max_tolerable_latency * 4;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
701
    raw_stream_buffer->timeoutrecv = timeoutrecv;
702
    raw_stream_buffer->n_pdlist = 0;
703
    raw_stream_buffer->pdlist = (NMXP_DATA_PROCESS **) NMXP_MEM_MALLOC(raw_stream_buffer->max_pdlist_items * sizeof(NMXP_DATA_PROCESS *));
704
705
706
707
708
709
710
711
712
    for(j=0; j<raw_stream_buffer->max_pdlist_items; j++) {
	raw_stream_buffer->pdlist[j] = NULL;
    }

}


void nmxp_raw_stream_free(NMXP_RAW_STREAM_DATA *raw_stream_buffer) {
    int j;
713
714
    if(raw_stream_buffer) {
	if(raw_stream_buffer->pdlist) {
715
	    for(j=0; j<raw_stream_buffer->n_pdlist; j++) {
716
717
		if(raw_stream_buffer->pdlist[j]) {
		    if(raw_stream_buffer->pdlist[j]->buffer) {
718
			NMXP_MEM_FREE(raw_stream_buffer->pdlist[j]->buffer);
719
720
721
			raw_stream_buffer->pdlist[j]->buffer = NULL;
		    }
		    if(raw_stream_buffer->pdlist[j]->pDataPtr) {
722
			NMXP_MEM_FREE(raw_stream_buffer->pdlist[j]->pDataPtr);
723
724
			raw_stream_buffer->pdlist[j]->pDataPtr = NULL;
		    }
725
		    NMXP_MEM_FREE(raw_stream_buffer->pdlist[j]);
726
		    raw_stream_buffer->pdlist[j] = NULL;
727
		}
728
	    }
729
	    NMXP_MEM_FREE(raw_stream_buffer->pdlist);
730
	    raw_stream_buffer->pdlist = NULL;
731
732
733
734
735
	}
    }
}


Matteo Quintiliani's avatar
Matteo Quintiliani committed
736
int nmxp_raw_stream_manage(NMXP_RAW_STREAM_DATA *p, NMXP_DATA_PROCESS *a_pd, int (*p_func_pd[NMXP_MAX_FUNC_PD]) (NMXP_DATA_PROCESS *), int n_func_pd) {
737
738
739
740
741
742
743
744
745
    int ret = 0;
    int send_again = 1;
    int seq_no_diff;
    double time_diff;
    double latency = 0.0;
    int j=0, k=0;
    int i_func_pd;
    char str_time[200];
    NMXP_DATA_PROCESS *pd = NULL;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
746
    int y, w;
747
748
    int count_null_element = 0;
    char netstachan[100];
749

750
    /* Allocate pd copy value from a_pd */
751
    if(a_pd) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
752
753
754
755
756
757
758
	/*
	if(a_pd->packet_type == 33 || a_pd->packet_type == 97) {
	    nmxp_data_log(a_pd);
	}
	*/

	/* Allocate memory for pd and copy a_pd */
759
	pd = (NMXP_DATA_PROCESS *) NMXP_MEM_MALLOC(sizeof(NMXP_DATA_PROCESS));
Matteo Quintiliani's avatar
Matteo Quintiliani committed
760
761
	memcpy(pd, a_pd, sizeof(NMXP_DATA_PROCESS));
	if(a_pd->length > 0) {
762
	    pd->buffer = NMXP_MEM_MALLOC(pd->length);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
763
764
765
766
767
	    memcpy(pd->buffer, a_pd->buffer, a_pd->length);
	} else {
	    pd->buffer = NULL;
	}
	if(a_pd->nSamp *  sizeof(int) > 0) {
768
	    pd->pDataPtr = (int *) NMXP_MEM_MALLOC(a_pd->nSamp * sizeof(int));
Matteo Quintiliani's avatar
Matteo Quintiliani committed
769
770
771
772
	    memcpy(pd->pDataPtr, a_pd->pDataPtr, a_pd->nSamp * sizeof(int));
	} else {
	    pd->pDataPtr = NULL;
	}
773
774
    } else {
	nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_RAWSTREAM,
775
		"nmxp_raw_stream_manage() passing NMXP_DATA_PROCESS pointer equal to NULL\n");
776
    }
777
    /* From here, use only pd */
778
779

    /* First time */
780
    if(p->last_seq_no_sent == -1  &&  pd) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
781
782
783
	if(p->timeoutrecv == 0) {
	    p->last_seq_no_sent = pd->seq_no - 1;
	    p->last_sample_time = pd->time;
784
	    p->last_latency = nmxp_data_latency(pd);;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
785
786
	} else {
	    p->last_seq_no_sent = 0;
787
788
	    p->last_sample_time = 0.0;
	    p->last_latency = 0.0;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
789
	}
790
	nmxp_data_to_str(str_time, pd->time);
791
	nmxp_log(NMXP_LOG_NORM, NMXP_LOG_D_RAWSTREAM,
792
793
794
795
796
		"%s.%s.%s [%d, %d] (%s + %.2f sec.) * First time nmxp_raw_stream_manage() * last_seq_no_sent=%d  last_sample_time=%.2f\n",
		NMXP_LOG_STR(pd->network), NMXP_LOG_STR(pd->station), NMXP_LOG_STR(pd->channel),
		pd->packet_type, pd->seq_no,
		NMXP_LOG_STR(str_time), (double) pd->nSamp / (double) pd->sampRate,
		 p->last_seq_no_sent, p->last_sample_time);
797
    }
Matteo Quintiliani's avatar
Matteo Quintiliani committed
798

799
800
801
    if(p->n_pdlist > 0) {
	latency = nmxp_data_latency(p->pdlist[0]);
    }
802

803
804
805
    /* Add pd and sort array, in case handle the first item */
    if( (p->n_pdlist >= p->max_pdlist_items || latency >= p->max_tolerable_latency)
	    && p->timeoutrecv <= 0 ) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
806

807
	/* Supposing p->pdlist is ordered, handle the first item and over write it.  */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
808
809
810
811
812
813
	if(p->n_pdlist > 0) {
	    seq_no_diff = p->pdlist[0]->seq_no - p->last_seq_no_sent;
	    time_diff = p->pdlist[0]->time - p->last_sample_time;
	    latency = nmxp_data_latency(p->pdlist[0]);
	    nmxp_data_to_str(str_time, p->pdlist[0]->time);
	    if( seq_no_diff > 0) {
814
		nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_RAWSTREAM,
815
816
817
818
819
820
			"%s.%s.%s [%d, %d] (%s + %.2f sec.) * Force handling packet * n_pdlist=%d  seq_no_diff=%d  time_diff=%.2fs  lat. %.1fs!\n",
			NMXP_LOG_STR(p->pdlist[0]->network), NMXP_LOG_STR(p->pdlist[0]->station), NMXP_LOG_STR(p->pdlist[0]->channel),
			p->pdlist[0]->packet_type, p->pdlist[0]->seq_no,
			NMXP_LOG_STR(str_time), (double) p->pdlist[0]->nSamp / (double) p->pdlist[0]->sampRate,
			p->n_pdlist,
			seq_no_diff, time_diff, latency);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
821
822
823
824
825
		for(i_func_pd=0; i_func_pd<n_func_pd; i_func_pd++) {
		    (*p_func_pd[i_func_pd])(p->pdlist[0]);
		}
		p->last_seq_no_sent = (p->pdlist[0]->seq_no);
		p->last_sample_time = (p->pdlist[0]->time + ((double) p->pdlist[0]->nSamp / (double) p->pdlist[0]->sampRate ));
826
		p->last_latency = nmxp_data_latency(p->pdlist[0]);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
827
828
	    } else {
		/* It should not occur */
829
830
831
832
833
834
835
		nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_RAWSTREAM,
			"%s.%s.%s [%d, %d] (%s + %.2f sec.) * SHOULD NOT OCCUR packet discarded * n_pdlist=%d  seq_no_diff=%d  time_diff=%.2fs  lat. %.1fs!\n",
			NMXP_LOG_STR(p->pdlist[0]->network), NMXP_LOG_STR(p->pdlist[0]->station), NMXP_LOG_STR(p->pdlist[0]->channel),
			p->pdlist[0]->packet_type, p->pdlist[0]->seq_no,
			NMXP_LOG_STR(str_time), (double) p->pdlist[0]->nSamp / (double) p->pdlist[0]->sampRate,
			p->n_pdlist,
			seq_no_diff, time_diff, latency);
836
837
	    }

Matteo Quintiliani's avatar
Matteo Quintiliani committed
838
839
	    /* Free handled packet */
	    if(p->pdlist[0]->buffer) {
840
		NMXP_MEM_FREE(p->pdlist[0]->buffer);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
841
842
843
		p->pdlist[0]->buffer = NULL;
	    }
	    if(p->pdlist[0]->pDataPtr) {
844
		NMXP_MEM_FREE(p->pdlist[0]->pDataPtr);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
845
846
847
		p->pdlist[0]->pDataPtr = NULL;
	    }
	    if(p->pdlist[0]) {
848
		NMXP_MEM_FREE(p->pdlist[0]);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
849
850
851
852
853
854
855
856
857
858
		p->pdlist[0] = NULL;
	    }
	    if(pd) {
		p->pdlist[0] = pd;
	    }
	} else {
	    if(pd) {
		p->n_pdlist = 1;
		p->pdlist[0] = pd;
	    }
859
860
	}
    } else {
861
862
863
	if(pd) {
	    p->pdlist[p->n_pdlist++] = pd;
	}
864
    }
865
866
867
868
869

    /* Check if some element in pdlist is NULL and remove it */
    y=0;
    while(y < p->n_pdlist) {
	if(p->pdlist[y] == NULL) {
870
	    count_null_element++;
871
872
873
874
875
876
877
878
879
880
	    /* Shift array */
	    for(w=y+1; w < p->n_pdlist; w++) {
		p->pdlist[w-1] = p->pdlist[w];
	     }
	    p->n_pdlist--;
	} else {
	    y++;
	}
    }

881
882
883
884
885
886
887
888
889
890
891
892
893
894
    if(count_null_element > 0) {
	if(p->n_pdlist > 0) {
	    snprintf(netstachan, 100, "%s.%s.%s",
		    NMXP_LOG_STR(p->pdlist[0]->network),
		    NMXP_LOG_STR(p->pdlist[0]->station),
		    NMXP_LOG_STR(p->pdlist[0]->channel));
	} else {
	    strncpy(netstachan, "Unknown", 100);
	}
	nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_ANY,
		"nmxp_raw_stream_manage() %d NULL elements in pdlist for %s.\n",
		count_null_element, netstachan);
    }

895
    /* Sort array */
896
897
    qsort(p->pdlist, p->n_pdlist, sizeof(NMXP_DATA_PROCESS *), nmxp_raw_stream_seq_no_compare);

898
    /* TODO Check for packet duplication in pd->pdlist*/
899
900

    /* Print array, only for debugging */
901
    /*
902
903
904
    if(p->n_pdlist > 1) {
	int y = 0;
	for(y=0; y < p->n_pdlist; y++) {
905
906
907
908
909
910
911
	    nmxp_data_to_str(str_time, p->pdlist[y]->time);
	    nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_RAWSTREAM,
		    "%s.%s.%s [%d, %d] (%s + %.2f sec.) * %02d n_pdlist=%d\n",
		    NMXP_LOG_STR(p->pdlist[y]->network), NMXP_LOG_STR(p->pdlist[y]->station), NMXP_LOG_STR(p->pdlist[y]->channel),
		    p->pdlist[y]->packet_type, p->pdlist[y]->seq_no,
		    NMXP_LOG_STR(str_time), (double) p->pdlist[y]->nSamp / (double) p->pdlist[y]->sampRate,
		    y, p->n_pdlist);
912
913
	}
    }
914
    */
915

916
    /* Condition for time-out (pd is NULL) */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
917
    if(!pd && p->n_pdlist > 0) {
918
919
920
921
922
923
924
925
926
927
928
	/* Log before changing values */
	nmxp_data_to_str(str_time, p->pdlist[0]->time);
	nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_RAWSTREAM,
		"%s.%s.%s [%d, %d] (%s + %.2f sec.) * pd is NULL and n_pdlist = %d > 0 *  last_seq_no_sent=%d, last_sample_time=%.2f\n",
		NMXP_LOG_STR(p->pdlist[0]->network), NMXP_LOG_STR(p->pdlist[0]->station), NMXP_LOG_STR(p->pdlist[0]->channel),
		p->pdlist[0]->packet_type, p->pdlist[0]->seq_no,
		NMXP_LOG_STR(str_time), (double) p->pdlist[0]->nSamp / (double) p->pdlist[0]->sampRate,
		p->n_pdlist,
		p->last_seq_no_sent, p->last_sample_time);

	/* Changing values */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
929
930
	p->last_seq_no_sent = p->pdlist[0]->seq_no - 1;
	p->last_sample_time = p->pdlist[0]->time;
931
	p->last_latency = nmxp_data_latency(p->pdlist[0]);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
932
    }
933
934
935
936
937
938
939
940
941
942
943

    /* Manage array and execute func_pd() */
    j=0;
    send_again = 1;
    while(send_again  &&  j < p->n_pdlist) {
	send_again = 0;
	seq_no_diff = p->pdlist[j]->seq_no - p->last_seq_no_sent;
	time_diff = p->pdlist[j]->time - p->last_sample_time;
	latency = nmxp_data_latency(p->pdlist[j]);
	nmxp_data_to_str(str_time, p->pdlist[j]->time);
	if(seq_no_diff <= 0) {
944
	    /* Duplicated packets: Discarded */
945
	    nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_RAWSTREAM,
946
947
948
949
950
		    "%s.%s.%s [%d, %d] (%s + %.2f sec.) * Packet discarded * seq_no_diff=%d  time_diff=%.2fs  lat %.1fs\n",
		    NMXP_LOG_STR(p->pdlist[j]->network), NMXP_LOG_STR(p->pdlist[j]->station), NMXP_LOG_STR(p->pdlist[j]->channel),
		    p->pdlist[j]->packet_type, p->pdlist[j]->seq_no, 
		    NMXP_LOG_STR(str_time), (double) p->pdlist[j]->nSamp / (double) p->pdlist[j]->sampRate,
		    seq_no_diff, time_diff, latency);
951
952
953
	    send_again = 1;
	    j++;
	} else if(seq_no_diff == 1) {
954
	    /* Handle current packet j */
955
956
957
958
	    for(i_func_pd=0; i_func_pd<n_func_pd; i_func_pd++) {
		(*p_func_pd[i_func_pd])(p->pdlist[j]);
	    }
	    if(time_diff > TIME_TOLLERANCE || time_diff < -TIME_TOLLERANCE) {
959
		nmxp_log(NMXP_LOG_ERR, NMXP_LOG_D_ANY,
960
961
962
963
964
965
			"%s.%s.%s [%d, %d] (%s + %.2f sec.) * Time is not correct * last_seq_no_sent=%d  seq_no_diff=%d  time_diff=%.2fs  lat. %.1fs\n",
		    NMXP_LOG_STR(p->pdlist[j]->network), NMXP_LOG_STR(p->pdlist[j]->station), NMXP_LOG_STR(p->pdlist[j]->channel), 
		    p->pdlist[j]->packet_type, p->pdlist[j]->seq_no,
		    str_time, (double) p->pdlist[j]->nSamp /  (double) p->pdlist[j]->sampRate,
		    p->last_seq_no_sent,
		    seq_no_diff, time_diff, latency);
966
967
968
	    }
	    p->last_seq_no_sent = p->pdlist[j]->seq_no;
	    p->last_sample_time = (p->pdlist[j]->time + ((double) p->pdlist[j]->nSamp / (double) p->pdlist[j]->sampRate ));
969
	    p->last_latency = nmxp_data_latency(p->pdlist[j]);
970
971
972
	    send_again = 1;
	    j++;
	} else {
973
	    nmxp_log(NMXP_LOG_WARN, NMXP_LOG_D_RAWSTREAM,
974
975
976
977
978
979
		    "%s.%s.%s [%d, %d] (%s + %.2f sec.) * seq_no_diff=%d > 1 * last_seq_no_sent=%d  j=%d  n_pdlist=%2d  time_diff=%.2fs  lat. %.1fs\n",
		    NMXP_LOG_STR(p->pdlist[j]->network), NMXP_LOG_STR(p->pdlist[j]->station), NMXP_LOG_STR(p->pdlist[j]->channel), 
		    p->pdlist[j]->packet_type, p->pdlist[j]->seq_no,
		    str_time, (double) p->pdlist[j]->nSamp /  (double) p->pdlist[j]->sampRate,
		    seq_no_diff, p->last_seq_no_sent, j, p->n_pdlist,
		    time_diff, latency);
980
981
982
983
984
985
986
987
	}
    }

    /* Shift and free j handled elements */
    if(j > 0) {
	for(k=0; k < p->n_pdlist; k++) {
	    if(k < j) {
		if(p->pdlist[k]->buffer) {
988
		    NMXP_MEM_FREE(p->pdlist[k]->buffer);