bladerf_lib.c 42.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.0  (the "License"); you may not use this file
 * except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

22 23 24 25
/** bladerf_lib.c
 *
 * Author: navid nikaein
 */
26 27 28 29 30 31


#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include "bladerf_lib.h"
32
#include "math.h"
33

34 35 36 37 38
/** @addtogroup _BLADERF_PHY_RF_INTERFACE_
 * @{
 */

//! Number of BladeRF devices 
nikaeinn's avatar
nikaeinn committed
39 40 41 42 43 44 45 46
#ifdef __SSE4_1__
#  include <smmintrin.h>
#endif
 
#ifdef __AVX2__
#  include <immintrin.h>
#endif

47
int num_devices=0;
48

49 50 51
/*These items configure the underlying asynch stream used by the the sync interface. 
 */

52 53
/*! \brief BladeRF Init function (not used at the moment)
 * \param device RF frontend parameters set by application
54
 * \returns 0 on success
55 56
 */
int trx_brf_init(openair0_device *device) {
57
   return 0;
58 59
}

60 61
/*! \brief get current timestamp
 *\param device the hardware to use 
62
 *\param module the bladeRf module
63
 *\returns timestamp of BladeRF
64
 */
65
 
nikaeinn's avatar
nikaeinn committed
66
openair0_timestamp trx_get_timestamp(openair0_device *device, bladerf_module module) {
67
  int status;
68 69
  struct bladerf_metadata meta;
  brf_state_t *brf = (brf_state_t*)device->priv;
nikaeinn's avatar
nikaeinn committed
70
  memset(&meta, 0, sizeof(meta));
71
  
nikaeinn's avatar
nikaeinn committed
72 73 74 75 76
  if ((status=bladerf_get_timestamp(brf->dev, module, &meta.timestamp)) != 0) {
    fprintf(stderr,"Failed to get current %s timestamp: %s\n",(module == BLADERF_MODULE_RX ) ? "RX" : "TX", bladerf_strerror(status));
    return -1; 
  } // else {printf("Current RX timestampe  0x%016"PRIx64"\n", meta.timestamp); }

77
  return meta.timestamp;
78 79
}

80
/*! \brief Start BladeRF
81 82
 * \param device the hardware to use 
 * \returns 0 on success
83 84
 */
int trx_brf_start(openair0_device *device) {
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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  brf_state_t *brf = (brf_state_t*)device->priv;
  int status;

  brf->meta_tx.flags = 0;

  if ((status = bladerf_sync_config(brf->dev,
          BLADERF_MODULE_TX,
          BLADERF_FORMAT_SC16_Q11_META,
          brf->num_buffers,
          brf->buffer_size,
          brf->num_transfers,
          100/*brf->tx_timeout_ms*/)) != 0 ) {
    fprintf(stderr,"Failed to configure TX sync interface: %s\n", bladerf_strerror(status));
    abort();
  }
  if ((status = bladerf_sync_config(brf->dev,
          BLADERF_MODULE_RX,
          BLADERF_FORMAT_SC16_Q11_META,
          brf->num_buffers,
          brf->buffer_size,
          brf->num_transfers,
          100/*brf->rx_timeout_ms*/)) != 0 ) {
    fprintf(stderr,"Failed to configure RX sync interface: %s\n", bladerf_strerror(status));
    abort();
  }
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_TX, true)) != 0) {
    fprintf(stderr,"Failed to enable TX module: %s\n", bladerf_strerror(status));
    abort();
  }
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_RX, true)) != 0) {
    fprintf(stderr,"Failed to enable RX module: %s\n", bladerf_strerror(status));
    abort();
  }

  if ((status=bladerf_calibrate_dc(brf->dev, BLADERF_MODULE_TX)) != 0) {
    fprintf(stderr,"Failed to calibrate TX DC: %s\n", bladerf_strerror(status));
    abort();
  }
  if ((status=bladerf_calibrate_dc(brf->dev, BLADERF_MODULE_RX)) != 0) {
    fprintf(stderr,"Failed to calibrate RX DC: %s\n", bladerf_strerror(status));
    abort();
  }
127

128
  return 0;
129 130
}

131
/*! \brief Called to send samples to the BladeRF RF target
132 133 134 135 136 137 138
      \param device pointer to the device structure specific to the RF hardware target
      \param timestamp The timestamp at whicch the first sample MUST be sent 
      \param buff Buffer which holds the samples
      \param nsamps number of samples to be sent
      \param cc index of the component carrier
      \param flags Ignored for the moment
      \returns 0 on success
139
*/ 
140
static int trx_brf_write(openair0_device *device,openair0_timestamp ptimestamp, void **buff, int nsamps, int cc, int flags) {
141
  
nikaeinn's avatar
nikaeinn committed
142
  int status;
143
  brf_state_t *brf = (brf_state_t*)device->priv;
144
  /* BRF has only 1 rx/tx chaine : is it correct? */
nikaeinn's avatar
nikaeinn committed
145
  int16_t *samples = (int16_t*)buff[0];
146
  
nikaeinn's avatar
nikaeinn committed
147 148 149 150 151 152 153
  //memset(&brf->meta_tx, 0, sizeof(brf->meta_tx));
  // When  BLADERF_META_FLAG_TX_NOW is used the timestamp is not used, so one can't schedule a tx 
  if (brf->meta_tx.flags == 0 ) 
    brf->meta_tx.flags = (BLADERF_META_FLAG_TX_BURST_START);// | BLADERF_META_FLAG_TX_BURST_END);// |  BLADERF_META_FLAG_TX_NOW);
  
  
  brf->meta_tx.timestamp= (uint64_t) (ptimestamp); 
navid's avatar
navid committed
154
  status = bladerf_sync_tx(brf->dev, samples, (unsigned int) nsamps, &brf->meta_tx, 2*brf->tx_timeout_ms);
nikaeinn's avatar
nikaeinn committed
155 156 157
 
  if (brf->meta_tx.flags == BLADERF_META_FLAG_TX_BURST_START) 
    brf->meta_tx.flags =  BLADERF_META_FLAG_TX_UPDATE_TIMESTAMP;
158
  
nikaeinn's avatar
nikaeinn committed
159

160
  if (status != 0) {
nikaeinn's avatar
nikaeinn committed
161
    //fprintf(stderr,"Failed to TX sample: %s\n", bladerf_strerror(status));
162
    brf->num_tx_errors++;
163
    brf_error(status);
navid's avatar
navid committed
164 165 166 167 168
  } else if (brf->meta_tx.status & BLADERF_META_STATUS_UNDERRUN){
    /* libbladeRF does not report this status. It is here for future use. */ 
    fprintf(stderr, "TX Underrun detected. %u valid samples were read.\n",  brf->meta_tx.actual_count);
    brf->num_underflows++;
  } 
nikaeinn's avatar
nikaeinn committed
169 170
  //printf("Provided TX timestampe  %u, meta timestame %u\n", ptimestamp,brf->meta_tx.timestamp);
  
navid's avatar
navid committed
171 172 173 174 175 176
  //    printf("tx status %d \n",brf->meta_tx.status);
  brf->tx_current_ts=brf->meta_tx.timestamp;
  brf->tx_actual_nsamps+=brf->meta_tx.actual_count;
  brf->tx_nsamps+=nsamps;
  brf->tx_count++;
  
177

178
  return nsamps; //brf->meta_tx.actual_count;
179 180
}

181 182 183 184 185 186 187 188 189
/*! \brief Receive samples from hardware.
 * Read \ref nsamps samples from each channel to buffers. buff[0] is the array for
 * the first channel. *ptimestamp is the time at which the first sample
 * was received.
 * \param device the hardware to use
 * \param[out] ptimestamp the time at which the first sample was received.
 * \param[out] buff An array of pointers to buffers for received samples. The buffers must be large enough to hold the number of samples \ref nsamps.
 * \param nsamps Number of samples. One sample is 2 byte I + 2 byte Q => 4 byte.
 * \param cc  Index of component carrier
190
 * \returns number of samples read
191
*/
192
static int trx_brf_read(openair0_device *device, openair0_timestamp *ptimestamp, void **buff, int nsamps, int cc) {
nikaeinn's avatar
nikaeinn committed
193 194

  int status=0;
195 196 197
  brf_state_t *brf = (brf_state_t*)device->priv;
  
  // BRF has only one rx/tx chain
nikaeinn's avatar
nikaeinn committed
198 199
  int16_t *samples = (int16_t*)buff[0];
  
200
  brf->meta_rx.actual_count = 0;
nikaeinn's avatar
nikaeinn committed
201
  brf->meta_rx.flags = BLADERF_META_FLAG_RX_NOW;
navid's avatar
navid committed
202
  status = bladerf_sync_rx(brf->dev, samples, (unsigned int) nsamps, &brf->meta_rx, 2*brf->rx_timeout_ms);
203
  
204
  //  printf("Current RX timestampe  %u, nsamps %u, actual %u, cc %d\n",  brf->meta_rx.timestamp, nsamps, brf->meta_rx.actual_count, cc);
nikaeinn's avatar
nikaeinn committed
205
   
206
  if (status != 0) {
207
    fprintf(stderr, "RX failed: %s\n", bladerf_strerror(status)); 
208
    //    printf("RX failed: %s\n", bladerf_strerror(status)); 
209 210 211
    brf->num_rx_errors++;
  } else if ( brf->meta_rx.status & BLADERF_META_STATUS_OVERRUN) {
    brf->num_overflows++;
212
    printf("RX overrun (%d) is detected. t=" "%" PRIu64 "Got %u samples. nsymps %d\n", 
213
	   brf->num_overflows,brf->meta_rx.timestamp,  brf->meta_rx.actual_count, nsamps);
nikaeinn's avatar
nikaeinn committed
214
  } 
215

nikaeinn's avatar
nikaeinn committed
216
  //printf("Current RX timestampe  %u\n",  brf->meta_rx.timestamp);
navid's avatar
navid committed
217 218 219 220 221 222
  //printf("[BRF] (buff %p) ts=0x%"PRIu64" %s\n",samples, brf->meta_rx.timestamp,bladerf_strerror(status));
  brf->rx_current_ts=brf->meta_rx.timestamp;
  brf->rx_actual_nsamps+=brf->meta_rx.actual_count;
  brf->rx_nsamps+=nsamps;
  brf->rx_count++;
  
223 224
  
  *ptimestamp = brf->meta_rx.timestamp;
nikaeinn's avatar
nikaeinn committed
225
 
226
  return nsamps; //brf->meta_rx.actual_count;
227 228 229

}

230 231 232
/*! \brief Terminate operation of the BladeRF transceiver -- free all associated resources 
 * \param device the hardware to use
 */
233
void trx_brf_end(openair0_device *device) {
234
abort();
235 236

  int status;
237
  brf_state_t *brf = (brf_state_t*)device->priv;
238
  // Disable RX module, shutting down our underlying RX stream
239
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_RX, false))  != 0) {
240 241
    fprintf(stderr, "Failed to disable RX module: %s\n", bladerf_strerror(status));
  }
242
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_TX, false))  != 0) {
243 244
    fprintf(stderr, "Failed to disable TX module: %s\n",  bladerf_strerror(status));
  }
245
  bladerf_close(brf->dev);
246 247
}

248 249 250 251
/*! \brief print the BladeRF statistics  
* \param device the hardware to use
* \returns  0 on success
*/
252 253 254 255 256 257
int trx_brf_get_stats(openair0_device* device) {

  return(0);

}

258 259 260 261
/*! \brief Reset the BladeRF statistics  
* \param device the hardware to use
* \returns  0 on success
*/
262 263 264 265 266 267
int trx_brf_reset_stats(openair0_device* device) {

  return(0);

}

268 269 270
/*! \brief Stop BladeRF
 * \param card the hardware to use
 * \returns 0 in success 
271
 */
Rohit Gupta's avatar
Rohit Gupta committed
272
int trx_brf_stop(openair0_device* device) {
273 274 275 276 277

  return(0);

}

278 279
/*! \brief Set frequencies (TX/RX)
 * \param device the hardware to use
280 281
 * \param openair0_cfg1 openair0 Config structure (ignored. It is there to comply with RF common API)
 * \param exmimo_dump_config (ignored)
282 283
 * \returns 0 in success 
 */
284
int trx_brf_set_freq(openair0_device* device, openair0_config_t *openair0_cfg1,int exmimo_dump_config) {
285

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
  int status;
  brf_state_t *brf = (brf_state_t *)device->priv;
  openair0_config_t *openair0_cfg = (openair0_config_t *)device->openair0_cfg;


  if ((status=bladerf_set_frequency(brf->dev, BLADERF_MODULE_TX, (unsigned int) openair0_cfg->tx_freq[0])) != 0){
    fprintf(stderr,"Failed to set TX frequency: %s\n",bladerf_strerror(status));
    brf_error(status);
  }else 
    printf("[BRF] set TX Frequency to %u\n", (unsigned int) openair0_cfg->tx_freq[0]);

  if ((status=bladerf_set_frequency(brf->dev, BLADERF_MODULE_RX, (unsigned int) openair0_cfg->rx_freq[0])) != 0){
    fprintf(stderr,"Failed to set RX frequency: %s\n",bladerf_strerror(status));
    brf_error(status);
  } else 
    printf("[BRF] set RX frequency to %u\n",(unsigned int)openair0_cfg->rx_freq[0]);

303 304 305
  return(0);

}
306 307 308

/*! \brief Set Gains (TX/RX)
 * \param device the hardware to use
309
 * \param openair0_cfg openair0 Config structure
310 311
 * \returns 0 in success 
 */
312
int trx_brf_set_gains(openair0_device* device, openair0_config_t *openair0_cfg) {
313 314 315 316 317

  return(0);

}

318 319


320 321 322 323
#define RXDCLENGTH 16384
int16_t cos_fsover8[8]  = {2047,   1447,      0,  -1448,  -2047,  -1448,     0,   1447};
int16_t cos_3fsover8[8] = {2047,  -1448,      0,   1447,  -2047,   1447,     0,  -1448};

324
/*! \brief calibration table for BladeRF */
325 326 327 328 329 330
rx_gain_calib_table_t calib_table_fx4[] = {
  {2300000000.0,53.5},
  {1880000000.0,57.0},
  {816000000.0,73.0},
  {-1,0}};

331 332 333 334
/*! \brief set RX gain offset from calibration table
 * \param openair0_cfg RF frontend parameters set by application
 * \param chain_index RF chain ID
 */
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
void set_rx_gain_offset(openair0_config_t *openair0_cfg, int chain_index) {

  int i=0;
  // loop through calibration table to find best adjustment factor for RX frequency
  double min_diff = 6e9,diff;
  
  while (openair0_cfg->rx_gain_calib_table[i].freq>0) {
    diff = fabs(openair0_cfg->rx_freq[chain_index] - openair0_cfg->rx_gain_calib_table[i].freq);
    printf("cal %d: freq %f, offset %f, diff %f\n",
	   i,
	   openair0_cfg->rx_gain_calib_table[i].freq,
	   openair0_cfg->rx_gain_calib_table[i].offset,diff);
    if (min_diff > diff) {
      min_diff = diff;
      openair0_cfg->rx_gain_offset[chain_index] = openair0_cfg->rx_gain_calib_table[i].offset;
    }
    i++;
  }
  
}

356 357 358
/*! \brief Calibrate LMSSDR RF 
 * \param device the hardware to use
 */
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
void calibrate_rf(openair0_device *device) {


  brf_state_t *brf = (brf_state_t *)device->priv;
  openair0_timestamp ptimestamp;
  int16_t *calib_buffp,*calib_tx_buffp;
  int16_t calib_buff[2*RXDCLENGTH];
  int16_t calib_tx_buff[2*RXDCLENGTH];
  int i,j,offI,offQ,offIold,offQold,offInew,offQnew,offphase,offphaseold,offphasenew,offgain,offgainold,offgainnew;
  int32_t meanI,meanQ,meanIold,meanQold;
  int cnt=0,loop;

  // put TX on a far-away frequency to avoid interference in RX band
  bladerf_set_frequency(brf->dev,BLADERF_MODULE_TX, (unsigned int) device->openair0_cfg->rx_freq[0] + 200e6);  
  // Set gains to close to max
  bladerf_set_gain(brf->dev, BLADERF_MODULE_RX, 60);
  bladerf_set_gain(brf->dev, BLADERF_MODULE_TX, 60);

  // fill TX buffer with fs/8 complex sinusoid
  j=0;
  for (i=0;i<RXDCLENGTH;i++) {
    calib_tx_buff[j++] = cos_fsover8[i&7];
    calib_tx_buff[j++] = cos_fsover8[(i+6)&7];  // sin
  }
  calib_buffp = &calib_buff[0];
  calib_tx_buffp = &calib_tx_buff[0];
  // Calibrate RX DC offset

  offIold=offQold=2048;
  bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_I,offIold);
  bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_Q,offQold);
  for (i=0;i<10;i++)
    trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
  
  for (meanIold=meanQold=i=j=0;i<RXDCLENGTH;i++) {
    meanIold+=calib_buff[j++];
    meanQold+=calib_buff[j++];
  }
  meanIold/=RXDCLENGTH;
  meanQold/=RXDCLENGTH;
  printf("[BRF] RX DC: (%d,%d) => (%d,%d)\n",offIold,offQold,meanIold,meanQold);

  offI=offQ=-2048;
  bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_I,offI);
  bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_Q,offQ);
  for (i=0;i<10;i++)
    trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
  
  for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
    meanI+=calib_buff[j++];
    meanQ+=calib_buff[j++];
  }
  meanI/=RXDCLENGTH;
  meanQ/=RXDCLENGTH;
  //  printf("[BRF] RX DC: (%d,%d) => (%d,%d)\n",offI,offQ,meanI,meanQ);

  while (cnt++ < 12) {

    offInew=(offIold+offI)>>1;
    offQnew=(offQold+offQ)>>1;

    if (meanI*meanI < meanIold*meanIold) {
      meanIold = meanI;
      offIold = offI;
      printf("[BRF] *** RX DC: offI %d => %d\n",offIold,meanI);
    }
    if (meanQ*meanQ < meanQold*meanQold) {
      meanQold = meanQ;
      offQold = offQ;
      printf("[BRF] *** RX DC: offQ %d => %d\n",offQold,meanQ);
    }
    offI = offInew;
    offQ = offQnew;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_I,offI);
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_Q,offQ);

    for (i=0;i<10;i++)
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
    
    for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
      meanI+=calib_buff[j++];
      meanQ+=calib_buff[j++];
    }
    meanI/=RXDCLENGTH;
    meanQ/=RXDCLENGTH;
    printf("[BRF] RX DC: (%d,%d) => (%d,%d)\n",offI,offQ,meanI,meanQ);
  }

  printf("[BRF] RX DC: (%d,%d) => (%d,%d)\n",offIold,offQold,meanIold,meanQold);
  bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_I,offIold);
  bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_LMS_DCOFF_Q,offQold);

  // TX DC offset
  // PUT TX as f_RX + fs/4
  // loop back BLADERF_LB_RF_LNA1
  bladerf_set_frequency(brf->dev,BLADERF_MODULE_TX, (unsigned int) device->openair0_cfg->rx_freq[0] + (unsigned int) device->openair0_cfg->sample_rate/4);  
  bladerf_set_loopback (brf->dev,BLADERF_LB_RF_LNA1);

  offIold=2048;
  bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_I,offIold);
  for (i=0;i<10;i++) {
    trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
461
    trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
  }
  for (meanIold=meanQold=i=j=0;i<RXDCLENGTH;i++) {
    switch (i&3) {
    case 0:
      meanIold+=calib_buff[j++];
      break;
    case 1:
      meanQold+=calib_buff[j++];
      break;
    case 2:
      meanIold-=calib_buff[j++];
      break;
    case 3:
      meanQold-=calib_buff[j++];
      break;
    }
  }
  //  meanIold/=RXDCLENGTH;
  //  meanQold/=RXDCLENGTH;
  printf("[BRF] TX DC (offI): %d => (%d,%d)\n",offIold,meanIold,meanQold);

  offI=-2048;
  bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_I,offI);
  for (i=0;i<10;i++) {
    trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
487
    trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
  }
  for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
    switch (i&3) {
    case 0:
      meanI+=calib_buff[j++];
      break;
    case 1:
      meanQ+=calib_buff[j++];
      break;
    case 2:
      meanI-=calib_buff[j++];
      break;
    case 3:
      meanQ-=calib_buff[j++];
      break;
    }
  }
  //  meanI/=RXDCLENGTH;
  //  meanQ/=RXDCLENGTH;
  printf("[BRF] TX DC (offI): %d => (%d,%d)\n",offI,meanI,meanQ);
  cnt = 0;
  while (cnt++ < 12) {

    offInew=(offIold+offI)>>1;
    if (meanI*meanI+meanQ*meanQ < meanIold*meanIold +meanQold*meanQold) {
      printf("[BRF] TX DC (offI): ([%d,%d]) => %d : %d\n",offIold,offI,offInew,meanI*meanI+meanQ*meanQ);
      meanIold = meanI;
      meanQold = meanQ;
      offIold = offI;
    }
    offI = offInew;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_I,offI);

    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
523
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    }
    for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
      switch (i&3) {
      case 0:
	meanI+=calib_buff[j++];
	break;
      case 1:
	meanQ+=calib_buff[j++];
	break;
      case 2:
	meanI-=calib_buff[j++];
	break;
      case 3:
	meanQ-=calib_buff[j++];
	break;
      }
    }
    //    meanI/=RXDCLENGTH;
    //   meanQ/=RXDCLENGTH;
    //    printf("[BRF] TX DC (offI): %d => (%d,%d)\n",offI,meanI,meanQ);
  }

  bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_I,offIold);

  offQold=2048;
  bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_Q,offQold);
  for (i=0;i<10;i++) {
    trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
552
    trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
  }
  // project on fs/4
  for (meanIold=meanQold=i=j=0;i<RXDCLENGTH;i++) {
    switch (i&3) {
    case 0:
      meanIold+=calib_buff[j++];
      break;
    case 1:
      meanQold+=calib_buff[j++];
      break;
    case 2:
      meanIold-=calib_buff[j++];
      break;
    case 3:
      meanQold-=calib_buff[j++];
      break;
    }
  }
  //  meanIold/=RXDCLENGTH;
  //  meanQold/=RXDCLENGTH;
  printf("[BRF] TX DC (offQ): %d => (%d,%d)\n",offQold,meanIold,meanQold);

  offQ=-2048;
  bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_Q,offQ);
  for (i=0;i<10;i++) {
    trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
579
    trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
  }
  for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
    switch (i&3) {
    case 0:
      meanI+=calib_buff[j++];
      break;
    case 1:
      meanQ+=calib_buff[j++];
      break;
    case 2:
      meanI-=calib_buff[j++];
      break;
    case 3:
      meanQ-=calib_buff[j++];
      break;
    }
  }
  //  meanI/=RXDCLENGTH;
  //  meanQ/=RXDCLENGTH;
  printf("[BRF] TX DC (offQ): %d => (%d,%d)\n",offQ,meanI,meanQ);

  cnt=0;
  while (cnt++ < 12) {

    offQnew=(offQold+offQ)>>1;
    if (meanI*meanI+meanQ*meanQ < meanIold*meanIold +meanQold*meanQold) {
      printf("[BRF] TX DC (offQ): ([%d,%d]) => %d : %d\n",offQold,offQ,offQnew,meanI*meanI+meanQ*meanQ);

      meanIold = meanI;
      meanQold = meanQ;
      offQold = offQ;
    }
    offQ = offQnew;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_Q,offQ);

    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
617
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    }
    for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
      switch (i&3) {
      case 0:
	meanI+=calib_buff[j++];
	break;
      case 1:
	meanQ+=calib_buff[j++];
	break;
      case 2:
	meanI-=calib_buff[j++];
	break;
      case 3:
	meanQ-=calib_buff[j++];
	break;
      }
    }
    //    meanI/=RXDCLENGTH;
    //   meanQ/=RXDCLENGTH;
    //    printf("[BRF] TX DC (offQ): %d => (%d,%d)\n",offQ,meanI,meanQ);
  }

  printf("[BRF] TX DC: (%d,%d) => (%d,%d)\n",offIold,offQold,meanIold,meanQold);

  bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_LMS_DCOFF_Q,offQold);

  // TX IQ imbalance
  for (loop=0;loop<2;loop++) {
    offphaseold=4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_PHASE,offphaseold);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
650
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    }
    // project on fs/8 (Image of TX signal in +ve frequencies)
    for (meanIold=meanQold=i=j=0;i<RXDCLENGTH;i++) {
      meanIold+= (calib_buff[j]*cos_fsover8[i&7] - calib_buff[j+1]*cos_fsover8[(i+2)&7])>>11;
      meanQold+= (calib_buff[j]*cos_fsover8[(i+2)&7] + calib_buff[j+1]*cos_fsover8[i&7])>>11;
      j+=2;
    }
    
    meanIold/=RXDCLENGTH;
    meanQold/=RXDCLENGTH;
    printf("[BRF] TX IQ (offphase): %d => (%d,%d)\n",offphaseold,meanIold,meanQold);
    
    offphase=-4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_PHASE,offphase);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
667
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    }
    // project on fs/8 (Image of TX signal in +ve frequencies)
    for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
      meanI+= (calib_buff[j]*cos_fsover8[i&7] - calib_buff[j+1]*cos_fsover8[(i+2)&7])>>11;
      meanQ+= (calib_buff[j]*cos_fsover8[(i+2)&7] + calib_buff[j+1]*cos_fsover8[i&7])>>11;
      j+=2;
    }
    
    meanI/=RXDCLENGTH;
    meanQ/=RXDCLENGTH;
    printf("[BRF] TX IQ (offphase): %d => (%d,%d)\n",offphase,meanI,meanQ);
    
    cnt=0;
    while (cnt++ < 13) {
      
      offphasenew=(offphaseold+offphase)>>1;
      printf("[BRF] TX IQ (offphase): ([%d,%d]) => %d : %d\n",offphaseold,offphase,offphasenew,meanI*meanI+meanQ*meanQ);
      if (meanI*meanI+meanQ*meanQ < meanIold*meanIold +meanQold*meanQold) {

	
	meanIold = meanI;
	meanQold = meanQ;
	offphaseold = offphase;
      }
      offphase = offphasenew;
      bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_PHASE,offphase);
      
      for (i=0;i<10;i++) {
	trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
697
	trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
      }
      // project on fs/8 (Image of TX signal in +ve frequencies)
      for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
	meanI+= (calib_buff[j]*cos_fsover8[i&7] - calib_buff[j+1]*cos_fsover8[(i+2)&7])>>11;
	meanQ+= (calib_buff[j]*cos_fsover8[(i+2)&7] + calib_buff[j+1]*cos_fsover8[i&7])>>11;
	j+=2;
      }
      meanI/=RXDCLENGTH;
      meanQ/=RXDCLENGTH;
      
      //    printf("[BRF] TX DC (offQ): %d => (%d,%d)\n",offQ,meanI,meanQ);
    }
    
    printf("[BRF] TX IQ offphase: %d => (%d,%d)\n",offphaseold,meanIold,meanQold);
    
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_PHASE,offphaseold);
    
    offgainold=4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_GAIN,offgainold);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
719
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
    }
    // project on fs/8 (Image of TX signal in +ve frequencies)
    for (meanIold=meanQold=i=j=0;i<RXDCLENGTH;i++) {
      meanIold+= (calib_buff[j]*cos_fsover8[i&7] - calib_buff[j+1]*cos_fsover8[(i+2)&7])>>11;
      meanQold+= (calib_buff[j]*cos_fsover8[(i+2)&7] + calib_buff[j+1]*cos_fsover8[i&7])>>11;
      j+=2;
    }
    
    meanIold/=RXDCLENGTH;
    meanQold/=RXDCLENGTH;
    printf("[BRF] TX IQ (offgain): %d => (%d,%d)\n",offgainold,meanIold,meanQold);
    
    offgain=-4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_GAIN,offgain);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
736
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
    }
    // project on fs/8 (Image of TX signal in +ve frequencies)
    for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
      meanI+= (calib_buff[j]*cos_fsover8[i&7] - calib_buff[j+1]*cos_fsover8[(i+2)&7])>>11;
      meanQ+= (calib_buff[j]*cos_fsover8[(i+2)&7] + calib_buff[j+1]*cos_fsover8[i&7])>>11;
      j+=2;
    }
    
    meanI/=RXDCLENGTH;
    meanQ/=RXDCLENGTH;
    printf("[BRF] TX IQ (offgain): %d => (%d,%d)\n",offgain,meanI,meanQ);
    
    cnt=0;
    while (cnt++ < 13) {
      
      offgainnew=(offgainold+offgain)>>1;
      if (meanI*meanI+meanQ*meanQ < meanIold*meanIold +meanQold*meanQold) {
	printf("[BRF] TX IQ (offgain): ([%d,%d]) => %d : %d\n",offgainold,offgain,offgainnew,meanI*meanI+meanQ*meanQ);
	
	meanIold = meanI;
	meanQold = meanQ;
	offgainold = offgain;
      }
      offgain = offgainnew;
      bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_GAIN,offgain);
      
      for (i=0;i<10;i++) {
	trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
765
	trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
      }
      // project on fs/8 (Image of TX signal in +ve frequencies)
      for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
	meanI+= (calib_buff[j]*cos_fsover8[i&7] - calib_buff[j+1]*cos_fsover8[(i+2)&7])>>11;
	meanQ+= (calib_buff[j]*cos_fsover8[(i+2)&7] + calib_buff[j+1]*cos_fsover8[i&7])>>11;
	j+=2;
      }
      meanI/=RXDCLENGTH;
      meanQ/=RXDCLENGTH;
      
      //    printf("[BRF] TX DC (offQ): %d => (%d,%d)\n",offQ,meanI,meanQ);
    }
    
    printf("[BRF] TX IQ offgain: %d => (%d,%d)\n",offgainold,meanIold,meanQold);
    
    bladerf_set_correction(brf->dev,BLADERF_MODULE_TX,BLADERF_CORR_FPGA_GAIN,offgainold);
  }

  // RX IQ imbalance
  for (loop=0;loop<2;loop++) {
    offphaseold=4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_PHASE,offphaseold);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
790
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    }
    // project on -3fs/8 (Image of TX signal in -ve frequencies)
    for (meanIold=meanQold=i=j=0;i<RXDCLENGTH;i++) {
      meanIold+= (calib_buff[j]*cos_3fsover8[i&7] - calib_buff[j+1]*cos_3fsover8[(i+2)&7])>>11;
      meanQold+= (calib_buff[j]*cos_3fsover8[(i+2)&7] + calib_buff[j+1]*cos_3fsover8[i&7])>>11;
      j+=2;
    }
    
    meanIold/=RXDCLENGTH;
    meanQold/=RXDCLENGTH;
    printf("[BRF] RX IQ (offphase): %d => (%d,%d)\n",offphaseold,meanIold,meanQold);
    
    offphase=-4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_PHASE,offphase);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
807
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
    }
    // project on -3fs/8 (Image of TX signal in -ve frequencies)
    for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
      meanI+= (calib_buff[j]*cos_3fsover8[i&7] - calib_buff[j+1]*cos_3fsover8[(i+2)&7])>>11;
      meanQ+= (calib_buff[j]*cos_3fsover8[(i+2)&7] + calib_buff[j+1]*cos_3fsover8[i&7])>>11;
      j+=2;
    }
    
    meanI/=RXDCLENGTH;
    meanQ/=RXDCLENGTH;
    printf("[BRF] RX IQ (offphase): %d => (%d,%d)\n",offphase,meanI,meanQ);
    
    cnt=0;
    while (cnt++ < 13) {
      
      offphasenew=(offphaseold+offphase)>>1;
      printf("[BRF] RX IQ (offphase): ([%d,%d]) => %d : %d\n",offphaseold,offphase,offphasenew,meanI*meanI+meanQ*meanQ);
      if (meanI*meanI+meanQ*meanQ < meanIold*meanIold +meanQold*meanQold) {

	
	meanIold = meanI;
	meanQold = meanQ;
	offphaseold = offphase;
      }
      offphase = offphasenew;
      bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_PHASE,offphase);
      
      for (i=0;i<10;i++) {
	trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
837
	trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
      }
      // project on -3fs/8 (Image of TX signal in -ve frequencies)
      for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
	meanI+= (calib_buff[j]*cos_3fsover8[i&7] - calib_buff[j+1]*cos_3fsover8[(i+2)&7])>>11;
	meanQ+= (calib_buff[j]*cos_3fsover8[(i+2)&7] + calib_buff[j+1]*cos_3fsover8[i&7])>>11;
	j+=2;
      }
      meanI/=RXDCLENGTH;
      meanQ/=RXDCLENGTH;
      
      //    printf("[BRF] TX DC (offQ): %d => (%d,%d)\n",offQ,meanI,meanQ);
    }
    
    printf("[BRF] RX IQ offphase: %d => (%d,%d)\n",offphaseold,meanIold,meanQold);
    
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_PHASE,offphaseold);
    
    offgainold=4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_GAIN,offgainold);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
859
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0,0);
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    }
    // project on -3fs/8 (Image of TX signal in +ve frequencies)
    for (meanIold=meanQold=i=j=0;i<RXDCLENGTH;i++) {
      meanIold+= (calib_buff[j]*cos_3fsover8[i&7] - calib_buff[j+1]*cos_3fsover8[(i+2)&7])>>11;
      meanQold+= (calib_buff[j]*cos_3fsover8[(i+2)&7] + calib_buff[j+1]*cos_3fsover8[i&7])>>11;
      j+=2;
    }
    
    meanIold/=RXDCLENGTH;
    meanQold/=RXDCLENGTH;
    printf("[BRF] RX IQ (offgain): %d => (%d,%d)\n",offgainold,meanIold,meanQold);
    
    offgain=-4096;
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_GAIN,offgain);
    for (i=0;i<10;i++) {
      trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
876
      trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
    }
    // project on 3fs/8 (Image of TX signal in -ve frequencies)
    for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
      meanI+= (calib_buff[j]*cos_3fsover8[i&7] - calib_buff[j+1]*cos_3fsover8[(i+2)&7])>>11;
      meanQ+= (calib_buff[j]*cos_3fsover8[(i+2)&7] + calib_buff[j+1]*cos_3fsover8[i&7])>>11;
      j+=2;
    }
    
    meanI/=RXDCLENGTH;
    meanQ/=RXDCLENGTH;
    printf("[BRF] RX IQ (offgain): %d => (%d,%d)\n",offgain,meanI,meanQ);
    
    cnt=0;
    while (cnt++ < 13) {
      
      offgainnew=(offgainold+offgain)>>1;
      if (meanI*meanI+meanQ*meanQ < meanIold*meanIold +meanQold*meanQold) {
	printf("[BRF] RX IQ (offgain): ([%d,%d]) => %d : %d\n",offgainold,offgain,offgainnew,meanI*meanI+meanQ*meanQ);
	
	meanIold = meanI;
	meanQold = meanQ;
	offgainold = offgain;
      }
      offgain = offgainnew;
      bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_GAIN,offgain);
      
      for (i=0;i<10;i++) {
	trx_brf_read(device, &ptimestamp, (void **)&calib_buffp, RXDCLENGTH, 0);
905
	trx_brf_write(device,ptimestamp+5*RXDCLENGTH, (void **)&calib_tx_buffp, RXDCLENGTH, 0, 0);
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
      }
      // project on -3fs/8 (Image of TX signal in -ve frequencies)
      for (meanI=meanQ=i=j=0;i<RXDCLENGTH;i++) {
	meanI+= (calib_buff[j]*cos_3fsover8[i&7] - calib_buff[j+1]*cos_3fsover8[(i+2)&7])>>11;
	meanQ+= (calib_buff[j]*cos_3fsover8[(i+2)&7] + calib_buff[j+1]*cos_3fsover8[i&7])>>11;
	j+=2;
      }
      meanI/=RXDCLENGTH;
      meanQ/=RXDCLENGTH;
      
      //    printf("[BRF] TX DC (offQ): %d => (%d,%d)\n",offQ,meanI,meanQ);
    }
    
    printf("[BRF] RX IQ offgain: %d => (%d,%d)\n",offgainold,meanIold,meanQold);
    
    bladerf_set_correction(brf->dev,BLADERF_MODULE_RX,BLADERF_CORR_FPGA_GAIN,offgainold);
  }

  bladerf_set_frequency(brf->dev,BLADERF_MODULE_TX, (unsigned int) device->openair0_cfg->tx_freq[0]);  
  bladerf_set_loopback(brf->dev,BLADERF_LB_NONE);
  bladerf_set_gain(brf->dev, BLADERF_MODULE_RX, (unsigned int) device->openair0_cfg->rx_gain[0]-device->openair0_cfg[0].rx_gain_offset[0]);
  bladerf_set_gain(brf->dev, BLADERF_MODULE_TX, (unsigned int) device->openair0_cfg->tx_gain[0]);
  //  write_output("blade_rf_test.m","rxs",calib_buff,RXDCLENGTH,1,1);
}

931 932 933
/*! \brief Initialize Openair BLADERF target. It returns 0 if OK 
 * \param device the hardware to use
 * \param openair0_cfg RF frontend parameters set by application
934
 * \returns 0 on success
935
 */
Rohit Gupta's avatar
Rohit Gupta committed
936
int device_init(openair0_device *device, openair0_config_t *openair0_cfg) {
937
  int status;
938 939
  brf_state_t *brf = (brf_state_t*)malloc(sizeof(brf_state_t));
  memset(brf, 0, sizeof(brf_state_t));
940
  /* device specific */
941 942
  //openair0_cfg->txlaunch_wait = 1;//manage when TX processing is triggered
  //openair0_cfg->txlaunch_wait_slotcount = 1; //manage when TX processing is triggered
943 944
  openair0_cfg->iq_txshift = 0;// shift
  openair0_cfg->iq_rxrescale = 15;//rescale iqs
945
  
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
  // init required params
  switch ((int)openair0_cfg->sample_rate) {
  case 30720000:
    openair0_cfg->samples_per_packet    = 2048;
    openair0_cfg->tx_sample_advance     = 0;
    break;
  case 15360000:
    openair0_cfg->samples_per_packet    = 2048;
    openair0_cfg->tx_sample_advance     = 0;
    break;
  case 7680000:
    openair0_cfg->samples_per_packet    = 1024;
    openair0_cfg->tx_sample_advance     = 0;
    break;
  case 1920000:
    openair0_cfg->samples_per_packet    = 256;
    openair0_cfg->tx_sample_advance     = 50;
    break;
  default:
    printf("Error: unknown sampling rate %f\n",openair0_cfg->sample_rate);
    exit(-1);
    break;
  }
969 970
  openair0_cfg->iq_txshift= 0;
  openair0_cfg->iq_rxrescale = 15; /*not sure*/
971
  openair0_cfg->rx_gain_calib_table = calib_table_fx4;
972

nikaeinn's avatar
nikaeinn committed
973 974 975
  //  The number of buffers to use in the underlying data stream
  brf->num_buffers   = 128;
  // the size of the underlying stream buffers, in samples
976
  brf->buffer_size   = (unsigned int) openair0_cfg->samples_per_packet;//*sizeof(int32_t); // buffer size = 4096 for sample_len of 1024
nikaeinn's avatar
nikaeinn committed
977 978 979
  brf->num_transfers = 16;
  brf->rx_timeout_ms = 0;  
  brf->tx_timeout_ms = 0;
980
  brf->sample_rate=(unsigned int)openair0_cfg->sample_rate;
981

nikaeinn's avatar
nikaeinn committed
982 983 984 985 986 987
  memset(&brf->meta_rx, 0, sizeof(brf->meta_rx));
  memset(&brf->meta_tx, 0, sizeof(brf->meta_tx));

  printf("\n[BRF] sampling_rate %d, num_buffers %d,  buffer_size %d, num transfer %d, timeout_ms (rx %d, tx %d)\n", 
	 brf->sample_rate, brf->num_buffers, brf->buffer_size,brf->num_transfers, brf->rx_timeout_ms, brf->tx_timeout_ms);
  
988
  if ((status=bladerf_open(&brf->dev, "")) != 0 ) {
989 990 991
    fprintf(stderr,"Failed to open brf device: %s\n",bladerf_strerror(status));
    brf_error(status);
  }
992 993 994 995 996 997 998 999 1000
  printf("[BRF] init dev %p\n", brf->dev);
  switch(bladerf_device_speed(brf->dev)){
  case BLADERF_DEVICE_SPEED_SUPER:
    printf("[BRF] Device operates at max speed\n");
    break;
  default:
    printf("[BRF] Device does not operates at max speed, change the USB port\n");
    brf_error(BLADERF_ERR_UNSUPPORTED);
  }
nikaeinn's avatar
nikaeinn committed
1001
  // RX  
1002 1003
  // Example of CLI output: RX Frequency: 2539999999Hz
  
1004
  if ((status=bladerf_set_frequency(brf->dev, BLADERF_MODULE_RX, (unsigned int) openair0_cfg->rx_freq[0])) != 0){
1005 1006
    fprintf(stderr,"Failed to set RX frequency: %s\n",bladerf_strerror(status));
    brf_error(status);
1007
  } else 
1008
    printf("[BRF] set RX frequency to %u\n",(unsigned int)openair0_cfg->rx_freq[0]);
1009
  
1010 1011


nikaeinn's avatar
nikaeinn committed
1012
  unsigned int actual_value=0;
1013
  if ((status=bladerf_set_sample_rate(brf->dev, BLADERF_MODULE_RX, (unsigned int) openair0_cfg->sample_rate, &actual_value)) != 0){
1014 1015
    fprintf(stderr,"Failed to set RX sample rate: %s\n", bladerf_strerror(status));
    brf_error(status);
nikaeinn's avatar
nikaeinn committed
1016
  }else  
1017
    printf("[BRF] set RX sample rate to %u, %u\n", (unsigned int) openair0_cfg->sample_rate, actual_value);
1018
 
nikaeinn's avatar
nikaeinn committed
1019

1020
  if ((status=bladerf_set_bandwidth(brf->dev, BLADERF_MODULE_RX, (unsigned int) openair0_cfg->rx_bw*2, &actual_value)) != 0){
1021 1022
    fprintf(stderr,"Failed to set RX bandwidth: %s\n", bladerf_strerror(status));
    brf_error(status);
1023
  }else 
1024
    printf("[BRF] set RX bandwidth to %u, %u\n",(unsigned int)openair0_cfg->rx_bw*2, actual_value);
1025
 
1026 1027
  set_rx_gain_offset(&openair0_cfg[0],0);
  if ((status=bladerf_set_gain(brf->dev, BLADERF_MODULE_RX, (int) openair0_cfg->rx_gain[0]-openair0_cfg[0].rx_gain_offset[0])) != 0) {
1028 1029
    fprintf(stderr,"Failed to set RX gain: %s\n",bladerf_strerror(status));
    brf_error(status);
1030
  } else 
1031
    printf("[BRF] set RX gain to %d (%d)\n",(int)(openair0_cfg->rx_gain[0]-openair0_cfg[0].rx_gain_offset[0]),(int)openair0_cfg[0].rx_gain_offset[0]);
1032 1033

  // TX
nikaeinn's avatar
nikaeinn committed
1034
  
1035
  if ((status=bladerf_set_frequency(brf->dev, BLADERF_MODULE_TX, (unsigned int) openair0_cfg->tx_freq[0])) != 0){
1036 1037
    fprintf(stderr,"Failed to set TX frequency: %s\n",bladerf_strerror(status));
    brf_error(status);
1038
  }else 
1039
    printf("[BRF] set TX Frequency to %u\n", (unsigned int) openair0_cfg->tx_freq[0]);
1040

1041
  if ((status=bladerf_set_sample_rate(brf->dev, BLADERF_MODULE_TX, (unsigned int) openair0_cfg->sample_rate, NULL)) != 0){
1042 1043
    fprintf(stderr,"Failed to set TX sample rate: %s\n", bladerf_strerror(status));
    brf_error(status);
1044
  }else 
1045
    printf("[BRF] set TX sampling rate to %u \n", (unsigned int) openair0_cfg->sample_rate);
1046

1047
  if ((status=bladerf_set_bandwidth(brf->dev, BLADERF_MODULE_TX,(unsigned int)openair0_cfg->tx_bw*2, NULL)) != 0){
nikaeinn's avatar
nikaeinn committed
1048
    fprintf(stderr, "Failed to set TX bandwidth: %s\n", bladerf_strerror(status));
1049
    brf_error(status);
1050
  }else 
1051
    printf("[BRF] set TX bandwidth to %u \n", (unsigned int) openair0_cfg->tx_bw*2);
1052

1053
  if ((status=bladerf_set_gain(brf->dev, BLADERF_MODULE_TX, (int) openair0_cfg->tx_gain[0])) != 0) {
1054 1055
    fprintf(stderr,"Failed to set TX gain: %s\n",bladerf_strerror(status));
    brf_error(status);
1056
  }else 
1057
    printf("[BRF] set the TX gain to %d\n", (int)openair0_cfg->tx_gain[0]);
nikaeinn's avatar
nikaeinn committed
1058
  
1059

nikaeinn's avatar
nikaeinn committed
1060
 /* Configure the device's TX module for use with the sync interface.
1061
   * SC16 Q11 samples *with* metadata are used. */
navid's avatar
navid committed
1062
  if ((status=bladerf_sync_config(brf->dev, BLADERF_MODULE_TX,BLADERF_FORMAT_SC16_Q11_META,brf->num_buffers,brf->buffer_size,brf->num_transfers,brf->tx_timeout_ms)) != 0 ) {
1063 1064
    fprintf(stderr,"Failed to configure TX sync interface: %s\n", bladerf_strerror(status));
     brf_error(status);
1065
  }else 
nikaeinn's avatar
nikaeinn committed
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
    printf("[BRF] configured TX  sync interface \n");

/* Configure the device's RX module for use with the sync interface.
   * SC16 Q11 samples *with* metadata are used. */
  if ((status=bladerf_sync_config(brf->dev, BLADERF_MODULE_RX, BLADERF_FORMAT_SC16_Q11_META,brf->num_buffers,brf->buffer_size,brf->num_transfers,brf->rx_timeout_ms)) != 0 ) {
    fprintf(stderr,"Failed to configure RX sync interface: %s\n", bladerf_strerror(status));
    brf_error(status);
  }else 
    printf("[BRF] configured Rx sync interface \n");

1076 1077 1078

   /* We must always enable the TX module after calling bladerf_sync_config(), and 
    * before  attempting to TX samples via  bladerf_sync_tx(). */
1079
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_TX, true)) != 0) {
1080 1081
    fprintf(stderr,"Failed to enable TX module: %s\n", bladerf_strerror(status));
    brf_error(status);
1082
  } else 
navid's avatar
navid committed
1083
    printf("[BRF] TX module enabled \n");
nikaeinn's avatar
nikaeinn committed
1084
 
nikaeinn's avatar
nikaeinn committed
1085 1086 1087 1088 1089 1090 1091 1092 1093
 /* We must always enable the RX module after calling bladerf_sync_config(), and 
    * before  attempting to RX samples via  bladerf_sync_rx(). */
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_RX, true)) != 0) {
    fprintf(stderr,"Failed to enable RX module: %s\n", bladerf_strerror(status));
    brf_error(status);
  }else 
    printf("[BRF] RX module enabled \n");

  // calibrate 
1094
    
nikaeinn's avatar
nikaeinn committed
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
 if ((status=bladerf_calibrate_dc(brf->dev, BLADERF_MODULE_TX)) != 0) {
    fprintf(stderr,"Failed to calibrate TX DC: %s\n", bladerf_strerror(status));
    brf_error(status);
  } else 
    printf("[BRF] TX module calibrated DC \n");
 
  if ((status=bladerf_calibrate_dc(brf->dev, BLADERF_MODULE_RX)) != 0) {
    fprintf(stderr,"Failed to calibrate RX DC: %s\n", bladerf_strerror(status));
    brf_error(status);
  }else 
    printf("[BRF] RX module calibrated DC \n");
1106
  
1107
  bladerf_log_set_verbosity(get_brf_log_level(openair0_cfg->log_level));
1108 1109 1110
  
  printf("BLADERF: Initializing openair0_device\n");
  device->Mod_id         = num_devices++;
1111
  device->type             = BLADERF_DEV; 
1112 1113 1114 1115
  device->trx_start_func = trx_brf_start;
  device->trx_end_func   = trx_brf_end;
  device->trx_read_func  = trx_brf_read;
  device->trx_write_func = trx_brf_write;
1116 1117 1118 1119 1120
  device->trx_get_stats_func   = trx_brf_get_stats;
  device->trx_reset_stats_func = trx_brf_reset_stats;
  device->trx_stop_func        = trx_brf_stop;
  device->trx_set_freq_func    = trx_brf_set_freq;
  device->trx_set_gains_func   = trx_brf_set_gains;
1121
  device->openair0_cfg = openair0_cfg;
1122
  device->priv = (void *)brf;
1123 1124 1125 1126

  calibrate_rf(device);

  //  memcpy((void*)&device->openair0_cfg,(void*)&openair0_cfg[0],sizeof(openair0_config_t));
1127

1128 1129 1130 1131 1132 1133 1134 1135 1136
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_TX, false)) != 0) {
    fprintf(stderr,"Failed to enable TX module: %s\n", bladerf_strerror(status));
    abort();
  }
  if ((status=bladerf_enable_module(brf->dev, BLADERF_MODULE_RX, false)) != 0) {
    fprintf(stderr,"Failed to enable RX module: %s\n", bladerf_strerror(status));
    abort();
  }

1137
  return 0;
1138 1139
}

1140 1141
/*! \brief bladeRF error report 
 * \param status 
1142
 * \returns 0 on success
1143
 */
1144
int brf_error(int status) {
1145
  
navid's avatar
navid committed
1146
  //exit(-1);
1147
  return status; // or status error code
1148 1149
}

1150

1151 1152
/*! \brief Open BladeRF from serial port
 * \param serial name of serial port on which to open BladeRF device
1153
 * \returns bladerf device structure
1154
 */
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
struct bladerf * open_bladerf_from_serial(const char *serial) {

  int status;
  struct bladerf *dev;
  struct bladerf_devinfo info;
  /* Initialize all fields to "don't care" wildcard values.
   *
   * Immediately passing this to bladerf_open_with_devinfo() would cause
   * libbladeRF to open any device on any available backend. */
  bladerf_init_devinfo(&info);
  /* Specify the desired device's serial number, while leaving all other
   * fields in the info structure wildcard values */
  strncpy(info.serial, serial, BLADERF_SERIAL_LENGTH - 1);
  info.serial[BLADERF_SERIAL_LENGTH - 1] = '\0';
  status = bladerf_open_with_devinfo(&dev, &info);
  
  if (status == BLADERF_ERR_NODEV) {
    printf("No devices available with serial=%s\n", serial);
    return NULL;
  } else if (status != 0) {
    fprintf(stderr, "Failed to open device with serial=%s (%s)\n", serial, bladerf_strerror(status));
    return NULL;
  } else {
    return dev;
  }
}
1181 1182 1183

/*! \brief Get BladeRF log level
 * \param log_level log level
1184
 * \returns log level of BLADERF device
1185
 */
1186 1187 1188
int get_brf_log_level(int log_level){

  int level=BLADERF_LOG_LEVEL_INFO;
nikaeinn's avatar
nikaeinn committed
1189
  return  BLADERF_LOG_LEVEL_DEBUG; // BLADERF_LOG_LEVEL_VERBOSE;// BLADERF_LOG_LEVEL_DEBUG; //
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  switch(log_level) {
  case LOG_DEBUG:
    level=BLADERF_LOG_LEVEL_DEBUG;
    break;
  case LOG_INFO:
    level= BLADERF_LOG_LEVEL_INFO;
    break;
  case LOG_WARNING:
    level=BLADERF_LOG_LEVEL_WARNING;
    break;
  case LOG_ERR:
    level=BLADERF_LOG_LEVEL_ERROR;
    break;
  case LOG_CRIT:
    level=BLADERF_LOG_LEVEL_CRITICAL;
    break;
  case LOG_EMERG:
    level = BLADERF_LOG_LEVEL_SILENT;
    break;
  default:
    break;
  }
  return level;
}
1214
/*@}*/