nmxp_base.c 12.1 KB
Newer Older
1 2
/*! \file
 *
Matteo Quintiliani's avatar
Matteo Quintiliani committed
3
 * \brief Base for Nanometrics Protocol Library
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * Author:
 * 	Matteo Quintiliani
 * 	Istituto Nazionale di Geofisica e Vulcanologia - Italy
 *	quintiliani@ingv.it
 *
 */

#include "nmxp_base.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>

Matteo Quintiliani's avatar
Matteo Quintiliani committed
27 28 29
#include "config.h"

#ifdef HAVE_LIBMSEED
30
#include <libmseed.h>
Matteo Quintiliani's avatar
Matteo Quintiliani committed
31
#endif
32

33

Matteo Quintiliani's avatar
Matteo Quintiliani committed
34 35 36 37
#define MAX_OUTDATA 4096



38 39 40 41 42 43 44 45 46 47
int nmxp_openSocket(char *hostname, int portNum)
{
  static int sleepTime = 1;
  int isock = 0;
  struct hostent *hostinfo = NULL;
  struct sockaddr_in psServAddr;
  struct in_addr hostaddr;
  
  if (!hostname)
  {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
48
    nmxp_log(1,0, "Empty host name?\n");
49 50 51 52
    return -1;
  }

  if ( (hostinfo = gethostbyname(hostname)) == NULL) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
53
    nmxp_log(1,0, "Cannot lookup host: %s\n", hostname);
54 55 56 57 58 59 60 61
    return -1;
  }

  while(1)
  {
    isock = socket (AF_INET, SOCK_STREAM, 0);
    if (isock < 0)
    {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
62
      nmxp_log (1,0, "Can't open stream socket\n");
63 64 65 66 67 68 69 70 71 72 73 74 75
      exit(1);
    }

    /* Fill in the structure "psServAddr" with the address of server
       that we want to connect with */
    memset (&psServAddr, 0, sizeof(psServAddr));
    psServAddr.sin_family = AF_INET;
    psServAddr.sin_port = htons((unsigned short) portNum);
    psServAddr.sin_addr = *(struct in_addr *)hostinfo->h_addr_list[0];

    /* Report action and resolved address */
    memcpy(&hostaddr.s_addr, *hostinfo->h_addr_list,
	   sizeof (hostaddr.s_addr));
Matteo Quintiliani's avatar
Matteo Quintiliani committed
76
    nmxp_log(0,1, "Attempting to connect to %s port %d\n",
77 78 79 80 81
	    inet_ntoa(hostaddr), portNum);

    if (connect(isock, (struct sockaddr *)&psServAddr, sizeof(psServAddr)) >= 0)
    {
      sleepTime = 1;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
82
      nmxp_log(0, 1, "Connection established: socket=%i,IP=%s,port=%d\n",
83 84 85 86 87
	      isock, inet_ntoa(hostaddr), portNum);
      return isock;
    }
    else
    {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
88
      nmxp_log(0, 1, "Trying again later...Sleeping\n");
89 90 91 92 93 94 95 96 97 98 99 100
      close (isock);
      sleep (sleepTime);
      sleepTime *= 2;
      if (sleepTime > NMXP_SLEEPMAX)
        sleepTime = NMXP_SLEEPMAX;
    }
  }
}


int nmxp_closeSocket(int isock)
{
Matteo Quintiliani's avatar
Matteo Quintiliani committed
101
    nmxp_log(0, 1, "Closed connection.\n");
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 134 135 136 137 138 139 140
    return close(isock);
}


int nmxp_send_ctrl(int isock, void* buffer, int length)
{
  int sendCount = send(isock, (char*) buffer, length, 0);
  
  if (sendCount != length)
    return NMXP_SOCKET_ERROR;

  return NMXP_SOCKET_OK;
}


int nmxp_recv_ctrl(int isock, void* buffer, int length)
{
  int recvCount;
  int recv_errno;
  char recv_errno_str[200];

  recvCount= recv(isock, (char*) buffer, length, MSG_WAITALL);
  recv_errno  = errno;

  if (recvCount != length) {
	  switch(recv_errno) {
		  case EAGAIN : strcpy(recv_errno_str, "EAGAIN"); break;
		  case EBADF : strcpy(recv_errno_str, "EBADF"); break;
		  case ECONNREFUSED : strcpy(recv_errno_str, "ECONNREFUSED"); break;
		  case EFAULT : strcpy(recv_errno_str, "EFAULT"); break;
		  case EINTR : strcpy(recv_errno_str, "EINTR"); break;
		  case EINVAL : strcpy(recv_errno_str, "EINVAL"); break;
		  case ENOMEM : strcpy(recv_errno_str, "ENOMEM"); break;
		  case ENOTCONN : strcpy(recv_errno_str, "ENOTCONN"); break;
		  case ENOTSOCK : strcpy(recv_errno_str, "ENOTSOCK"); break;
		  default:
			  strcpy(recv_errno_str, "DEFAULT_NO_VALUE");
			  break;
	  }
141
    nmxp_log(0, 1, "nmxp_recv_ctrl(): (recvCount != length) %d != %d - errno = %d (%s)\n", recvCount, length, recv_errno, recv_errno_str);
142 143 144 145 146 147 148 149
	    
    return NMXP_SOCKET_ERROR;
  }
  
  return NMXP_SOCKET_OK;
}


150
int nmxp_sendHeader(int isock, NMXP_MSG_CLIENT type, int32_t length)
151
{  
Matteo Quintiliani's avatar
Matteo Quintiliani committed
152
    NMXP_MESSAGE_HEADER msg;
153 154 155 156 157

    msg.signature = htonl(NMX_SIGNATURE);
    msg.type      = htonl(type);
    msg.length    = htonl(length);

Matteo Quintiliani's avatar
Matteo Quintiliani committed
158
    return nmxp_send_ctrl(isock, &msg, sizeof(NMXP_MESSAGE_HEADER));
159 160 161
}


162
int nmxp_receiveHeader(int isock, NMXP_MSG_SERVER *type, int32_t *length)
163 164
{  
    int ret ;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
165
    NMXP_MESSAGE_HEADER msg;
166

Matteo Quintiliani's avatar
Matteo Quintiliani committed
167
    ret = nmxp_recv_ctrl(isock, &msg, sizeof(NMXP_MESSAGE_HEADER));
168 169 170 171 172 173 174 175 176

    *type = 0;
    *length = 0;

    if(ret == NMXP_SOCKET_OK) {
	msg.signature = ntohl(msg.signature);
	msg.type      = ntohl(msg.type);
	msg.length    = ntohl(msg.length);

Matteo Quintiliani's avatar
Matteo Quintiliani committed
177
	nmxp_log(0,1, "nmxp_receiveHeader(): signature = %d, type = %d, length = %d\n",
178 179 180 181 182
		    msg.signature, msg.type, msg.length);

	if (msg.signature != NMX_SIGNATURE)
	{
	    ret = NMXP_SOCKET_ERROR;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
183
	    nmxp_log(1,0, "nmxp_receiveHeader(): signature mismatches. signature = %d, type = %d, length = %d\n",
184 185 186 187 188 189 190 191 192 193 194
		    msg.signature, msg.type, msg.length);
	} else {
	    *type = msg.type;
	    *length = msg.length;
	}
    }

    return ret;
}


195
int nmxp_sendMessage(int isock, NMXP_MSG_CLIENT type, void *buffer, int32_t length) {
196 197 198 199 200 201 202 203 204 205 206
    int ret;
    ret = nmxp_sendHeader(isock, type, length);
    if( ret == NMXP_SOCKET_OK) {
	if(buffer && length > 0) {
	    ret = nmxp_send_ctrl(isock, buffer, length);
	}
    }
    return ret;
}


207
int nmxp_receiveMessage(int isock, NMXP_MSG_SERVER *type, void **buffer, int32_t *length) {
208 209 210 211 212
    int ret;
    *buffer = NULL;
    *length = 0;

    ret = nmxp_receiveHeader(isock, type, length);
Matteo Quintiliani's avatar
Matteo Quintiliani committed
213

214
    if( ret == NMXP_SOCKET_OK) {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
215 216 217 218 219 220 221 222 223
	if (*length > 0) {
	    *buffer = malloc(*length);
	    ret = nmxp_recv_ctrl(isock, *buffer, *length);

	    if(*type == NMXP_MSG_ERROR) {
		nmxp_log(1,0, "Received ErrorMessage: %s\n", *buffer);
	    }

	}
224
    } else {
Matteo Quintiliani's avatar
Matteo Quintiliani committed
225
	nmxp_log(1,0, "Error in nmxp_receiveMessage()\n");
226
    }
Matteo Quintiliani's avatar
Matteo Quintiliani committed
227

228 229 230
    return ret;
}

231

232
NMXP_DATA_PROCESS *nmxp_processDecompressedData(char* buffer_data, int length_data, NMXP_CHAN_LIST *channelList, const char *network_code)
233 234 235 236 237 238 239 240 241
{
  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;
Matteo Quintiliani's avatar
Matteo Quintiliani committed
242
  int32_t outdata[MAX_OUTDATA];
243

244 245
  char station_code[20];
  char channel_code[20];
246 247 248 249 250 251 252 253 254

  static NMXP_DATA_PROCESS pd;

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

  memcpy(&pTime, &buffer_data[4], 8);
255
  if ( swap ) { nmxp_data_swap_8b((int64_t *) &pTime); }
256 257 258 259 260 261 262

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

  /* There should be (length_data - 20) bytes of data as 32-bit ints here */
Matteo Quintiliani's avatar
Matteo Quintiliani committed
263 264
  memcpy(outdata , (int32_t *) &buffer_data[20], length_data - 20);
  pDataPtr = outdata;
265 266 267 268 269 270 271

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

272 273
  if(!nmxp_chan_cpy_sta_chan(nmxp_chan_lookupName(pKey, channelList), station_code, channel_code)) {
    nmxp_log(1,0, "Channel name not in STN.CHAN format: %s\n", nmxp_chan_lookupName(pKey, channelList));
274 275 276 277 278
  }
  
  nmxp_data_init(&pd);

  pd.key = pKey;
279 280 281
  if(network_code) {
      strcpy(pd.network, network_code);
  }
282 283
  if(station_code[0] != 0) {
      strncpy(pd.station, station_code, STATION_LENGTH);
284
  }
285 286
  if(channel_code[0] != 0) {
      strncpy(pd.channel, channel_code, CHANNEL_LENGTH);
287
  }
288
  pd.packet_type = NMXP_MSG_DECOMPRESSED;
289 290 291 292 293
  pd.x0 = -1;
  pd.xn = -1;
  pd.x0n_significant = 0;
  // TODO
  // pd.oldest_seq_no = ;
294 295 296 297 298 299 300 301 302 303 304 305
  // pd.seq_no = ;
  pd.time = pTime;
  pd.buffer = buffer_data;
  pd.length = length_data;
  pd.nSamp = pNSamp;
  pd.pDataPtr = pDataPtr;
  pd.sampRate = pSampRate;

  return &pd;
}


306
NMXP_DATA_PROCESS *nmxp_processCompressedData(char* buffer_data, int length_data, NMXP_CHAN_LIST *channelList, const char *network_code)
307 308 309 310 311 312 313
{
    int32_t   pKey      = 0;
    double    pTime     = 0.0;
    int32_t   pNSamp    = 0;
    int32_t   pSampRate = 0;
    int32_t  *pDataPtr  = 0;

314 315
    char station_code[20];
    char channel_code[20];
316 317 318

    static NMXP_DATA_PROCESS pd;

319
    int32_t nmx_rate_code_to_sample_rate[32] = {
320 321 322 323 324
	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};

325
	int32_t nmx_oldest_sequence_number;
326 327
	char nmx_hdr[25];
	unsigned char nmx_ptype;
328
	int32_t nmx_seconds;
329
	double nmx_seconds_double;
330 331
	int16_t nmx_ticks, nmx_instr_id;
	int32_t nmx_seqno;
332
	unsigned char nmx_sample_rate;
333 334
	int32_t nmx_x0;
	int32_t rate_code, chan_code, this_sample_rate;
335

336
	int32_t comp_bytecount;
337 338
	unsigned char *indata;
	int32_t outdata[MAX_OUTDATA];
339 340
	int32_t nout, i, k;
	int32_t prev_xn;
341

342
	// TOREMOVE int my_order = get_my_wordorder();
Matteo Quintiliani's avatar
Matteo Quintiliani committed
343
	int my_host_is_bigendian = nmxp_data_bigendianhost();
344
	nmxp_log(0, 1, "my_host_is_bigendian %d\n", my_host_is_bigendian);
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

	memcpy(&nmx_oldest_sequence_number, buffer_data, 4);
	nmxp_log(0, 1, "Oldest sequence number = %d\n", nmx_oldest_sequence_number);

	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.   */
	    nmxp_log (1,0, "Filler packet - discarding\n");
	    //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);

367 368
	const uint32_t high_scale = 4096 * 2048;
	const uint32_t high_scale_p = 4096 * 4096;
369 370
	/* check if nmx_x0 is negative like as signed 3-byte int */
	if( (nmx_x0 & high_scale) ==  high_scale) {
371
	    // nmxp_log(0, 1, "WARNING: changed nmx_x0, old value = %d\n",  nmx_x0);
372 373
	    nmx_x0 -= high_scale_p;
	}
374 375
	/* TOREMOVE if (my_order != SEED_LITTLE_ENDIAN) { */
	if (my_host_is_bigendian) {
376
	    nmxp_data_swap_4b ((int32_t *)&nmx_seconds);
377 378 379
	    nmxp_data_swap_2b (&nmx_ticks);
	    nmxp_data_swap_2b (&nmx_instr_id);
	    nmxp_data_swap_4b (&nmx_seqno);
380
	    nmx_x0 = nmx_x0 >> 8;
381
	    nmxp_data_swap_4b (&nmx_x0);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
	    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];

	nmxp_log(0, 1, "nmx_ptype          = %d\n", nmx_ptype);
	nmxp_log(0, 1, "nmx_seconds        = %d\n", nmx_seconds);
	nmxp_log(0, 1, "nmx_ticks          = %d\n", nmx_ticks);

	nmxp_log(0, 1, "nmx_seconds_double = %f\n", nmx_seconds_double);
	nmxp_log(0, 1, "nmx_x0             = %d\n", nmx_x0);

	nmxp_log(0, 1, "nmx_instr_id       = %d\n", nmx_instr_id);
	nmxp_log(0, 1, "nmx_seqno          = %d\n", nmx_seqno);
	nmxp_log(0, 1, "nmx_sample_rate    = %d\n", nmx_sample_rate);
	nmxp_log(0, 1, "this_sample_rate    = %d\n", this_sample_rate);

	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) {
		nmxp_log (1,0, "comp_bytecount = %d, i+17 = %d\n",
			comp_bytecount, i+17);
		exit(1);
	    }
	    if (nout+16 > MAX_OUTDATA)  {
		nmxp_log (1,0, "Output buffer size too small\n");
		exit(1);
	    }
	    k = nmxp_data_unpack_bundle (outdata+nout,indata+i,&prev_xn);
	    if (k < 0) nmxp_log (1,0, "Break: (k=%d) %s %d\n", k, __FILE__,  __LINE__);
	    if (k < 0) break;
	    nout += k;
	    /* prev_xn = outdata[nout-1]; */
	}
	nout--;

	nmxp_log(0, 1, "Unpacked %d samples.\n", nout);

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

	pTime = nmx_seconds_double;

	pDataPtr = outdata;

	pNSamp = nout;

	pSampRate = this_sample_rate;

438 439
	if(!nmxp_chan_cpy_sta_chan(nmxp_chan_lookupName(pKey, channelList), station_code, channel_code)) {
	    nmxp_log(1,0, "Channel name not in STN.CHAN format: %s\n", nmxp_chan_lookupName(pKey, channelList));
440
	}
441 442
  
	nmxp_log(0, 1, "Channel key %d for %s.%s\n", pKey, station_code, channel_code);
443 444 445 446

	nmxp_data_init(&pd);

	pd.key = pKey;
447 448 449
	if(network_code) {
	    strcpy(pd.network, network_code);
	}
450 451
	if(station_code[0] != 0) {
	    strncpy(pd.station, station_code, STATION_LENGTH);
452
	}
453 454
	if(channel_code[0] != 0) {
	    strncpy(pd.channel, channel_code, CHANNEL_LENGTH);
455
	}
456 457
	pd.packet_type = nmx_ptype;
	pd.x0 = nmx_x0;
458
	pd.xn = pDataPtr[nout];
459
	pd.x0n_significant = 1;
460
	pd.oldest_seq_no = nmx_oldest_sequence_number;
461 462 463 464 465 466 467 468 469 470 471
	pd.seq_no = nmx_seqno;
	pd.time = pTime;
	pd.buffer = buffer_data;
	pd.length = length_data;
	pd.nSamp = pNSamp;
	pd.pDataPtr = pDataPtr;
	pd.sampRate = pSampRate;

	return &pd;
}