Guest User

alice

a guest
Jan 16th, 2015
685
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 11.18 KB | None | 0 0
  1. #include <libbladeRF.h>
  2. #define _USE_MATH_DEFINES
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <stdint.h>
  7. #include <string.h>
  8.  
  9. #define NUM_SAMPLES (512)
  10.  
  11. #define NUM_XFERS 1
  12.  
  13. struct bladerf *dev = NULL ;
  14. int16_t rx_samples[2*2*NUM_SAMPLES] ;
  15.  
  16. /***************************************************************************/
  17. /* Moving average functions                                                */
  18. /***************************************************************************/
  19.  
  20. struct ma {
  21.     int num;
  22.     int idx;
  23.     int total;
  24.     int *samps;
  25. };
  26.  
  27. void ma_clear(struct ma *ma) {
  28.     memset(ma->samps, 0, sizeof(int) * ma->num);
  29.     ma->idx = 0;
  30.     ma->total = 0;
  31. }
  32.  
  33. int ma_create(struct ma *ma) {
  34.     ma->samps = (int *)malloc(sizeof(int) * ma->num);
  35.     if (ma->samps == NULL)
  36.         return 1;
  37.     ma_clear(ma);
  38.  
  39.     return 0;
  40. }
  41.  
  42. int g = 0;
  43. int moving_avg(struct ma *ma, int sample) {
  44.     ma->total -= ma->samps[ma->idx];
  45.     ma->samps[ma->idx] = sample;
  46.     ma->idx++;
  47.     ma->idx %= ma->num;
  48.     ma->total += sample;
  49.     return ma->total/ma->num;
  50. }
  51.  
  52. /***************************************************************************/
  53. /* Packet deserialization functions                                        */
  54. /***************************************************************************/
  55.  
  56. void deserialize(unsigned char *ptr, char *ser_buf, int len) {
  57.     int i, j, p;
  58.     p = 0;
  59.     len /= 8;
  60.     for (i = 0; i < len; i++) {
  61.         ptr[i] = 0;
  62.         for (j = 0; j < 8; j++) {
  63.             ptr[i] |= ((ser_buf[p++] == '1' ? 1 : 0) << (7 - j));
  64.         }
  65.     }
  66.     ptr[i] = 0;
  67. }
  68.  
  69. struct packet {
  70.     unsigned int preamble;
  71.     unsigned int id;
  72.     unsigned int prn;
  73. #define PRIZE_NONE    0
  74. #define PRIZE_PAYPAL  1
  75. #define PRIZE_BITCOIN 2
  76.     int prize;
  77.     char recipient[40];
  78. };
  79.  
  80. #define PACKET_SZ sizeof(struct packet)
  81.  
  82. /***************************************************************************/
  83. /* Packet decoding and modulation functions                                */
  84. /***************************************************************************/
  85.  
  86. char demod[1000];
  87. char demanchester[500];
  88. unsigned int pkt_id = 0;
  89. unsigned int pkt_prn = 0;
  90. unsigned int victory_time = 0;
  91. void analyze() {
  92.     struct packet pkt;
  93.     int len;
  94.     int i, j;
  95.     int word;
  96.     int good;
  97.  
  98.     len = strlen(demod);
  99.     printf("len: %d\n", len);
  100.     printf("raw: %s\n", demod);
  101.  
  102.     good = 1;
  103.  
  104.     printf("Manchester:\n");
  105.     j = 0;
  106.     for (i = 0; i < len; i+=2) {
  107.         printf("%c%c", demod[i], (demod[i] == demod[i+1]) ? 'X' : '.');
  108.         /* Manchester decoding found an error bit */
  109.         if (demod[i] == demod[i+1])
  110.             good = 0;
  111.         demanchester[j++] = demod[i];
  112.     }
  113.     printf("\n");
  114.  
  115.     printf("Demanchester. len = %d:\n", len);
  116.     for (i = 0; i < len; i+=2) {
  117.         printf("%c", demod[i]);
  118.     }
  119.     printf("\n");
  120.  
  121.     printf("Grouped binary:\n");
  122.     for (i = 0; i < len; i+=2) {
  123.         if (((len - i) % 16) == 0) printf(" ");
  124.         printf("%c", demod[i]);
  125.     }
  126.     printf("\n");
  127.  
  128.     printf("Grouped binary in hex:\n");
  129.     word = 0;
  130.     for (i = 0; i < len; i+=2) {
  131.         if (((len - i) % 16) == 0) {
  132.             printf(" %.2x", word);
  133.             word = 0;
  134.         }
  135.         word = (word<<1) | (demod[i] - '0');
  136.     }
  137.     printf("good = %d\n", good);
  138.  
  139.     /* The packet passed Manchester decoding, so deserialize it */
  140.     if (good) {
  141.         deserialize((unsigned char *)&pkt, demanchester, sizeof(pkt));
  142.         printf("☻packet: id = %d, prn = %d | pkt_id = %d, pkt_prn = %d\n", pkt.id, pkt.prn, pkt_id, pkt_prn);
  143.         /* Make sure no one is replaying a previous transmission */
  144.         if (pkt.id == pkt_id && pkt.prn == pkt_prn) {
  145.             /* Enforce 5 minutes between victories */
  146.             if (victory_time + 5 < time(NULL)) {
  147.                 pkt_id++;
  148.                 pkt_prn = rand();
  149.                 if (pkt.prize != PRIZE_NONE) {
  150.                     victory_time = time(NULL);
  151.                     printf("WINNER! Good packet from Bob:");
  152.                 } else {
  153.                     printf("Good packet received from Bob:");
  154.                 }
  155.             } else {
  156.                 printf("Victory timer hasn't yet elapsed: ");
  157.             }
  158.             printf("id(%d) prn(%d) prize(%d) recipient(%s)\n",
  159.                     pkt.id, pkt.prn, pkt.prize, pkt.recipient);
  160.         }
  161.     }
  162. }
  163.  
  164. int main(int argc, char *argv[])
  165. {
  166.    int status;
  167.    unsigned int actual;
  168.    struct bladerf_rational_rate rational_actual, samplerate = { 0, 1500000, 1 } ;
  169.  
  170.    int lock, cnt;
  171.    int i, j, idx, pwr, ma;
  172.  
  173.    int dc_i, dc_q;
  174.  
  175.    struct ma detect;
  176.    struct ma phase;
  177.    int falling;
  178.    int sp;
  179.    int done;
  180.    int demodidx;
  181.    float phi, prev_phi, dphi_dt;
  182.  
  183.  
  184.    /* Increase verbosity */
  185.    bladerf_log_set_verbosity(BLADERF_LOG_LEVEL_DEBUG);
  186.  
  187.    /* Open the device */
  188.    status = bladerf_open(&dev, "") ;
  189.    if( status < 0 ) {
  190.        fprintf( stderr, "bladerf_open() error: %s\n", bladerf_strerror(status) );
  191.        goto close_device;
  192.    }
  193.  
  194.    /* Set the frequency */
  195.    status = bladerf_set_frequency(dev, BLADERF_MODULE_RX, 314500000) ;
  196.    if( status < 0 ) {
  197.        fprintf( stderr, "bladerf_set_frequency() RX error: %s\n", bladerf_strerror(status) );
  198.        goto close_device;
  199.    }
  200.  
  201.    /* Set the bandwidth */
  202.    status = bladerf_set_bandwidth(dev, BLADERF_MODULE_RX, 1500000, &actual) ;
  203.    if( status < 0 ) {
  204.        fprintf( stderr, "bladerf_set_bandwidth() RX error: %s\n", bladerf_strerror(status) );
  205.        goto close_device;
  206.    }
  207.  
  208.    /* Set the samplerate */
  209.  
  210.    status = bladerf_set_rational_sample_rate(dev, BLADERF_MODULE_RX, &samplerate, &rational_actual) ;
  211.    if( status < 0 ) {
  212.        fprintf( stderr, "bladerf_set_sample_rate() RX error: %s\n", bladerf_strerror(status) );
  213.        goto close_device;
  214.    }
  215.    bladerf_set_lna_gain(dev, BLADERF_LNA_GAIN_MAX);
  216.    bladerf_set_rxvga1(dev, BLADERF_RXVGA1_GAIN_MAX);
  217.    bladerf_set_rxvga2(dev, 6);
  218.  
  219.    /* Configure the sync stream */
  220.    status = bladerf_sync_config(
  221.        dev,
  222.        BLADERF_MODULE_RX,
  223.        BLADERF_FORMAT_SC16_Q11,
  224.        128,
  225.        2048,
  226.        NUM_XFERS,
  227.        2000);
  228.    if( status < 0 ) {
  229.        fprintf( stderr, "bladerf_sync_config() RX error: %s\n", bladerf_strerror(status) ) ;
  230.    }
  231.  
  232.    status = bladerf_enable_module(dev, BLADERF_MODULE_RX, true) ;
  233.    if( status < 0 ) {
  234.        fprintf( stderr, "bladerf_enable_module() RX error: %s\n", bladerf_strerror(status) );
  235.        goto close_device;
  236.    }
  237.  
  238.  
  239.    /* Determine DC offset to increase dynamic range and mitigate effects of DC offset */
  240.    dc_i = dc_q = 0;
  241.    status = bladerf_sync_rx(dev, (void *)rx_samples, NUM_SAMPLES, NULL, 1000);
  242.    idx = 0;
  243.    for (i = 0; i < NUM_SAMPLES; i++, idx+=2) {
  244.        dc_i += rx_samples[idx];
  245.        dc_q += rx_samples[idx+1];
  246.    }
  247.  
  248.    dc_i /= NUM_SAMPLES;
  249.    dc_q /= NUM_SAMPLES;
  250.  
  251.    /* Detection moving average is 100 samples long */
  252.    detect.num = 100;
  253.    ma_create(&detect);
  254.    /* Demoulation moving average is 35 samples long */
  255.    phase.num = 35;
  256.    ma_create(&phase);
  257.  
  258.    cnt = 0;
  259.  
  260.    // prep the PRNG
  261.    srand(0x1337BEEF);
  262.    // skip ahead
  263.    for (i = 0; i < 1337; i++)
  264.        rand();
  265.  
  266.    pkt_prn = rand();
  267.    lock=0;
  268.    while(1) {
  269.        status = bladerf_sync_rx(dev, (void *)rx_samples, NUM_SAMPLES, NULL, 1000);
  270.        idx = 0;
  271.        for (i = 0; i < NUM_SAMPLES; i++, idx += 2) {
  272.            /* Account for DC offset */
  273.            rx_samples[idx]   -= dc_i;
  274.            rx_samples[idx+1] -= dc_q;
  275.            cnt++;
  276.  
  277.            if (lock == 0) {
  278.                /* Currently not receiving a packet, look for an signal whose
  279.                 * moving averaged energy goes abouve "10000" */
  280.  
  281.                /* the energy of the current sample || I + j * Q || is given by:
  282.                 * energy = sqrt(I * I + Q * Q) */
  283.                ma = moving_avg(&detect, rx_samples[idx] * rx_samples[idx] + rx_samples[idx+1] * rx_samples[idx+1]);
  284.  
  285.                if (ma > 10000) {
  286.                    /* Strong energy signal detected start looking for its
  287.                     * falling edge then start demodulation */
  288.                    prev_phi = 0;
  289.  
  290.                    /* Ensure that no other packet is accidentally decoded for
  291.                     * another 350000 samples */
  292.                    lock = 350000;
  293.                    ma_clear(&detect);
  294.                    ma_clear(&phase);
  295.                    cnt = 0;
  296.                    falling = 0;
  297.                    done = 0;
  298.                    demodidx = 0;
  299.                }
  300.            } else {
  301.                lock--;
  302.  
  303.                /* If the packet has been decoded wait a few more samples to
  304.                 * ensure that ISI and transmitter anomalies don't accidentally
  305.                 * trigger another packet detection */
  306.                if (done) continue;
  307.  
  308.                /* Find the angle of the IQ sample by computing tan^-1(I/Q) */
  309.                phi = atan2f(rx_samples[idx], rx_samples[idx+1]);
  310.  
  311.                /* Unwind the phasor */
  312.                dphi_dt = prev_phi - phi;
  313.                if (dphi_dt < - M_PI)
  314.                    dphi_dt += 2 * M_PI;
  315.                else if (dphi_dt > M_PI)
  316.                    dphi_dt -= 2 * M_PI;
  317.                prev_phi = phi;
  318.  
  319.                ma = moving_avg(&phase, 1000 * dphi_dt);
  320.  
  321.                /* `falling` is used to find the falling edge of the first long
  322.                 * synchronization pulse */
  323.                if (falling == 0 && ma < 2100 && cnt > 100) {
  324.                    falling = 1;
  325.                    printf("First symbol of the first long synchronization pulse\n");
  326.                    /* the first symbol is sampled 187 samples after the falling
  327.                     * edge */
  328.                    sp = 750/4;
  329.                }
  330.  
  331.                if (falling) {
  332.                    if (sp == 0) {
  333.                        /* Demodulate 2000+/-100 radians/s as '1'
  334.                         * demodulate 2200+/-100 radians/s as '0'
  335.                         * detect anything else as an end of packet */
  336.                        if (ma > 1900 && ma < 2100)
  337.                            demod[demodidx++] = '1';
  338.                        else if (ma > 2100 && ma < 2300)
  339.                            demod[demodidx++] = '0';
  340.                        else {
  341.                            /* As previously described, the modem has detected an
  342.                             * invalid symbol so it means the packet may have
  343.                             * ended, so analyze the packet */
  344.                            demod[demodidx++] = 0;
  345.                            analyze();
  346.                            done = 1;
  347.                        }
  348.  
  349.                        /* Safety check */
  350.                        if (demodidx >= 1000)
  351.                            demodidx = 0;
  352.  
  353.                        /* Reload the sampling countdown variable */
  354.                        sp = 750/2;
  355.                    } else {
  356.                        /* Continue counting down the sampling time variable */
  357.                        sp--;
  358.                    }
  359.                }
  360.  
  361.            }
  362.        }
  363.    }
  364.  
  365. close_device:
  366.    bladerf_close(dev) ;
  367.    return status ;
  368. }
Advertisement
Add Comment
Please, Sign In to add comment