nmxp.c 11.9 KB
Newer Older
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*! \file
 *
 * \brief Nanometrics Protocol Libray
 *
 * Author:
 * 	Matteo Quintiliani
 * 	Istituto Nazionale di Geofisica e Vulcanologia - Italy
 *	quintiliani@ingv.it
 *
 */

#include "nmxp.h"

#include <stdio.h>
15
#include <stdlib.h>
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
16
17
#include <string.h>

18
19
20
21
22
#include <qlib2.h>

/* private variables */
int my_order = -1;

Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
23

24
25
int nmxp_sendConnect(int isock) {
    return nmxp_sendMessage(isock, NMXPMSG_CONNECT, NULL, 0);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
26
27
}

28
29
int nmxp_sendTerminateSubscription(int isock, enum NMXP_REASON_SHUTDOWN reason, char *message) {
    return nmxp_sendMessage(isock, NMXPMSG_TERMINATESUBSCRIPTION, message, ((message)? strlen(message)-1 : 0));
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
30
31
}

32
int nmxp_receiveChannelList(int isock, nmxp_ChannelList **pchannelList) {
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
33
34
35
36
37
38
39
40
41
    int ret;
    int i;

    enum NMXP_MSG_SERVER type;
    void *buffer;
    uint32_t length;

    *pchannelList = NULL;

42
    ret = nmxp_receiveMessage(isock, &type, &buffer, &length);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
43
44

    if(type != NMXPMSG_CHANNELLIST) {
45
	nmxp_gen_log(1, 0, "Type %d is not NMXPMSG_CHANNELLIST!\n", type);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
46
47
48
49
50
    } else {

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

51
	nmxp_gen_log(0, 1, "number of channels %d\n", (*pchannelList)->number);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
52
53
54
55
56
	
	// TODO check

	for(i=0; i < (*pchannelList)->number; i++) {
	    (*pchannelList)->channel[i].key = ntohl((*pchannelList)->channel[i].key);
57
	    nmxp_gen_log(0, 1, "%d %s\n", (*pchannelList)->channel[i].key, (*pchannelList)->channel[i].name);
Matteo Quintiliani's avatar
Start    
Matteo Quintiliani committed
58
59
60
61
62
63
64
65
	}

    }

    return ret;
}


66
int nmxp_sendAddTimeSeriesChannel(int isock, nmxp_ChannelList *channelList, uint32_t shortTermCompletion, uint32_t out_format, enum NMXP_BUFFER_FLAG buffer_flag) {
67
68
69
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
    int ret;
    uint32_t buffer_length = 16 + (4 * channelList->number); 
    char *buffer = malloc(buffer_length);
    uint32_t app, i, disp;

    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;

96
    ret = nmxp_sendMessage(isock, NMXPMSG_ADDTIMESERIESCHANNELS, buffer, buffer_length);
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

    if(buffer) {
	free(buffer);
    }
    return ret;
}


/***********************************************************************
 *  unpack_bundle:                                                     
 *      Unpack a 17-byte Nanometrics compressed data bundle.           
 *      Return the number of unpacked data samples, -1 if null bundle. 
 *
 * Author:  Doug Neuhauser
 *          UC Berkeley Seismological Laboratory
 *          doug@seismo.berkeley.edu
 ************************************************************************/
int unpack_bundle (int *outdata, unsigned char *indata, int *prev)
{         
	int nsamples = 0;
	int d4[4];
	short int d2[2];
	int cb[4];  
	int i, j, k;
	unsigned char cbits;

	cbits = (unsigned char)indata[0];
	if (cbits == 9) return (-1);
	++indata;

	/* Get the compression bits for the bundle. */
	for (i=0,j=6; j>=0; i++,j-=2) {
		cb[i] = (cbits>>j) & 3;
	}       

	for (j=0; j<4; j++) {
		/*
134
		nmxp_gen_log (0,0, "cb[%d]=%d\n", j, cb[j]);
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
		*/
		switch (cb[j]) 
		{   
			case 0:       /* not used     */
				k=0;
				break;       
			case 1:       /* 4 byte diffs */
				d4[0] = (signed char)indata[0];
				d4[1] = (signed char)indata[1];
				d4[2] = (signed char)indata[2];
				d4[3] = (signed char)indata[3];
				k=4;
				break;
			case 2:       /* 2 16-bit diffs */
				memcpy (&d2[0],indata,2);
				memcpy (&d2[1],indata+2,2);
				if (my_order != SEED_LITTLE_ENDIAN) {
					swab2 (&d2[0]);
					swab2 (&d2[1]);
				}
				d4[0] = d2[0];
				d4[1] = d2[1];
				k=2;
				break;
			case 3:       /* 1 32-bit diff */
				memcpy (&d4[0],indata,4);
				if (my_order != SEED_LITTLE_ENDIAN) {
					swab4 (&d4[0]);
				}
				k=1;
				break;
		}
		indata += 4;

		for (i=0; i<k; i++) {
			*outdata = *prev + d4[i];
			/*
172
				nmxp_gen_log(0,0, "val = %d, diff[%d] = %d, *prev = %d\n",
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
						*outdata, i, d4[i], *prev);
						*/
			*prev = *outdata;

			outdata++;
			++nsamples;
		}
	}
	return (nsamples);
}


/**************************************************************************

  Function:  processData

  Purpose:  processes compressed data from the server and sends them
            to the controlling SeedLink server.

 ------------------------------------------------------------------------*/
193
void nmxp_processDecompressedData(char* buffer, int length, nmxp_ChannelList *channelList)
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
{
  int32_t   netInt    = 0;
  int32_t   pKey      = 0;
  double    pTime     = 0.0;
  int32_t   pNSamp    = 0;
  int32_t   pSampRate = 0;
  int32_t  *pDataPtr  = 0;
  int       swap      = 0;
  int       idx;

  char *sta = 0;      /* The station code */
  char *chan = 0;     /* The channel code */

  /* copy the header contents into local fields and swap */
  memcpy(&netInt, &buffer[0], 4);
  pKey = ntohl(netInt);
  if ( pKey != netInt ) { swap = 1; }

  memcpy(&pTime, &buffer[4], 8);
  if ( swap ) { swab8(&pTime); }

  memcpy(&netInt, &buffer[12], 4);
  pNSamp = ntohl(netInt);
  memcpy(&netInt, &buffer[16], 4);
  pSampRate = ntohl(netInt);

  /* There should be (length - 20) bytes of data as 32-bit ints here */
  pDataPtr = (int32_t *) &buffer[20];

  /* Swap the data samples to host order */
  for ( idx=0; idx < pNSamp; idx++ ) {
      netInt = ntohl(pDataPtr[idx]);
      pDataPtr[idx] = netInt;
  }

  /* Lookup the station and channel code */
  sta = strdup(lookupChannelName(pKey, channelList));
  if ( (chan = strchr(sta, '.')) == NULL ) {
232
    nmxp_gen_log(1,0, "Channel name not in STN.CHAN format: %s\n", sta);
233
234
235
236
237
238
239
240
    free(sta);
    return;
  }
  *chan++ = '\0';
  
  /* Send it off to the controlling SeedLink server */
  /*
  if ( send_raw_depoch(sta, chan, pTime, 0, 100, pDataPtr, pNSamp) < 0 ) {
241
    nmxp_gen_log(1,0, "cannot send data to seedlink: %s", strerror(errno));
242
243
244
245
    exit(1);
  }
  */

246
  nmxp_gen_log(0, 0, "%10d %5s_%3s %10.4f, %04d, %04d, %03d\n", pKey, sta, chan, pTime, length, pNSamp, pSampRate);
247
248
  
  /* print out header and/or data for different packet types */
249
  nmxp_gen_log(0,1, "Received uncompressed data for stream %ld (%s_%s)\n",
250
	  pKey, sta, chan);
251
  nmxp_gen_log(0,1, "  length: %d, nsamp: %d, samprate: %d, time: %f\n",
252
253
254
255
256
	  length, pNSamp, pSampRate, pTime);
  
  free(sta);
}

257
void nmxp_processCompressedData(char* buffer_data, int length_data, nmxp_ChannelList *channelList)
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
{
    int32_t   pKey      = 0;
    double    pTime     = 0.0;
    int32_t   pNSamp    = 0;
    int32_t   pSampRate = 0;
    int32_t  *pDataPtr  = 0;

    char *sta = 0;      /* The station code */
    char *chan = 0;     /* The channel code */

    const int nmx_rate_code_to_sample_rate[32] = {
	0,1,2,5,10,20,40,50,
	80,100,125,200,250,500,1000,25,
	120,0,0,0,0,0,0,0,
	0,0,0,0,0,0,0,0};

	int nmx_oldest_sequence_number;
	char nmx_hdr[25];
	unsigned char nmx_ptype;
	unsigned int nmx_seconds;
	double nmx_seconds_double;
	short int nmx_ticks, nmx_instr_id;
	int nmx_seqno;
	unsigned char nmx_sample_rate;
	int nmx_x0;
	int rate_code, chan_code, this_sample_rate;

	int comp_bytecount;
	unsigned char *indata;
#define MAX_OUTDATA 4096
	int32_t outdata[MAX_OUTDATA];
	int nout, i, k;
	int prev_xn;

	my_order = get_my_wordorder();
293
	nmxp_gen_log(0, 1, "my_order is %d\n", my_order);
294
295

	memcpy(&nmx_oldest_sequence_number, buffer_data, 4);
296
	nmxp_gen_log(0, 1, "Oldest sequence number = %d\n", nmx_oldest_sequence_number);
297
298
299
300
301
302

	memcpy(nmx_hdr, buffer_data+4, 17);
	/* Decode the Nanometrics packet header bundle. */
	memcpy (&nmx_ptype, nmx_hdr+0, 1);
	if ( (nmx_ptype & 0xf) == 9) {
	    /* Filler packet.  Discard entire packet.   */
303
	    nmxp_gen_log (1,0, "Filler packet - discarding\n");
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
	    //m continue;
	    exit(0);
	}

	nmx_x0 = 0;
	memcpy (&nmx_seconds, nmx_hdr+1, 4);
	memcpy (&nmx_ticks, nmx_hdr+5, 2);
	memcpy (&nmx_instr_id, nmx_hdr+7, 2);
	memcpy (&nmx_seqno, nmx_hdr+9, 4);
	memcpy (&nmx_sample_rate, nmx_hdr+13, 1);
	memcpy (&nmx_x0, nmx_hdr+14, 3);

	const unsigned int high_scale = 4096 * 2048;
	const unsigned int high_scale_p = 4096 * 4096;
	/* check if nmx_x0 is negative like as signed 3-byte int */
	if( (nmx_x0 & high_scale) ==  high_scale) {
320
	    // nmxp_gen_log(0, 0, "WARNING: changed nmx_x0, old value = %d\n",  nmx_x0);
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
	    nmx_x0 -= high_scale_p;
	}
	if (my_order != SEED_LITTLE_ENDIAN) {
	    swab4 ((int *)&nmx_seconds);
	    swab2 (&nmx_ticks);
	    swab2 (&nmx_instr_id);
	    swab4 (&nmx_seqno);
	    nmx_x0 = nmx_x0 >> 8;
	    swab4 (&nmx_x0);
	    nmx_x0 = nmx_x0 >> 8;
	}
	nmx_seconds_double = (double) nmx_seconds + ( (double) nmx_ticks / 10000.0 );
	rate_code = nmx_sample_rate>>3;
	chan_code = nmx_sample_rate&7;
	this_sample_rate = nmx_rate_code_to_sample_rate[rate_code];

337
338
339
	nmxp_gen_log(0, 1, "nmx_ptype          = %d\n", nmx_ptype);
	nmxp_gen_log(0, 1, "nmx_seconds        = %d\n", nmx_seconds);
	nmxp_gen_log(0, 1, "nmx_ticks          = %d\n", nmx_ticks);
340

341
342
	nmxp_gen_log(0, 1, "nmx_seconds_double = %f\n", nmx_seconds_double);
	nmxp_gen_log(0, 1, "nmx_x0             = %d\n", nmx_x0);
343

344
345
346
347
	nmxp_gen_log(0, 1, "nmx_instr_id       = %d\n", nmx_instr_id);
	nmxp_gen_log(0, 1, "nmx_seqno          = %d\n", nmx_seqno);
	nmxp_gen_log(0, 1, "nmx_sample_rate    = %d\n", nmx_sample_rate);
	nmxp_gen_log(0, 1, "this_sample_rate    = %d\n", this_sample_rate);
348
349
350
351
352
353
354
355
356
357

	comp_bytecount = length_data-21;
	indata = (unsigned char *) buffer_data + 21;

	/* Unpack the data bundles, each 17 bytes long. */
	prev_xn = nmx_x0;
	outdata[0] = nmx_x0;
	nout = 1;
	for (i=0; i<comp_bytecount; i+=17) {
	    if (i+17>comp_bytecount) {
358
		nmxp_gen_log (1,0, "comp_bytecount = %d, i+17 = %d\n",
359
360
361
362
			comp_bytecount, i+17);
		exit(1);
	    }
	    if (nout+16 > MAX_OUTDATA)  {
363
		nmxp_gen_log (1,0, "Output buffer size too small\n");
364
365
366
		exit(1);
	    }
	    k = unpack_bundle (outdata+nout,indata+i,&prev_xn);
367
	    if (k < 0) nmxp_gen_log (1,0, "Break: %d\n", __LINE__);
368
369
370
371
372
373
	    if (k < 0) break;
	    nout += k;
	    /* prev_xn = outdata[nout-1]; */
	}
	nout--;

374
	nmxp_gen_log(0, 1, "Unpacked %d samples.\n", nout);
375
376
377
378
379
380
381
382
383
384
385
386

	pKey = (nmx_instr_id << 16) | ( 1 << 8) | ( chan_code);

	pTime = nmx_seconds_double;

	pDataPtr = outdata;

	pNSamp = nout;

	/* Lookup the station and channel code */
	sta = strdup(lookupChannelName(pKey, channelList));
	if ( (chan = strchr(sta, '.')) == NULL ) {
387
	    nmxp_gen_log(1,0, "Channel name not in STN.CHAN format: %s\n", sta);
388
389
390
391
392
	    free(sta);
	    return;
	}
	*chan++ = '\0';

393
	nmxp_gen_log(0, 1, "Channel key %d for %s.%s\n", pKey, sta, chan);
394
395
396
397

	/* Send it off to the controlling SeedLink server */
	/*
	  f ( send_raw_depoch(sta, chan, pTime, 0, 100, pDataPtr, pNSamp) < 0 ) {
398
	    nmxp_gen_log(1,0, "cannot send data to seedlink: %s", strerror(errno));
399
400
401
402
	    exit(1);
	}
	*/

403
	nmxp_gen_log(0, 0, "%10d %5s_%3s %10.4f, %04d, %04d, %03d\n", pKey, sta, chan, pTime, length_data, pNSamp, pSampRate);
404
405

	/* print out header and/or data for different packet types */
406
	nmxp_gen_log(0,2, "Received compressed data for stream %ld (%s_%s)\n",
407
		pKey, sta, chan);
408
	nmxp_gen_log(0,2, "  length: %d, nsamp: %d, samprate: %d, time: %f\n",
409
410
411
412
413
		length_data, pNSamp, pSampRate, pTime);

	free(sta);
}

414
int nmxp_receiveCompressedData(int isock, nmxp_ChannelList *channelList) {
415
416
417
418
419
420
    int ret;

    enum NMXP_MSG_SERVER type;
    void *buffer;
    uint32_t length;

421
    ret = nmxp_receiveMessage(isock, &type, &buffer, &length);
422
423

    if(type != NMXPMSG_COMPRESSED) {
424
	nmxp_gen_log(1, 0, "Type %d is not NMXPMSG_COMPRESSED!\n", type);
425
426
    } else {

427
	nmxp_processCompressedData(buffer, length, channelList);
428
429
430
431
432
    }

    return ret;
}

433
int nmxp_receiveDecompressedData(int isock, nmxp_ChannelList *channelList) {
434
435
436
437
438
439
    int ret;

    enum NMXP_MSG_SERVER type;
    void *buffer;
    uint32_t length;

440
    ret = nmxp_receiveMessage(isock, &type, &buffer, &length);
441
442

    if(type != NMXPMSG_DECOMPRESSED) {
443
	nmxp_gen_log(1, 0, "Type %d is not NMXPMSG_DECOMPRESSED!\n", type);
444
445
    } else {

446
	nmxp_processDecompressedData(buffer, length, channelList);
447
448
449
450
451
    }

    return ret;
}