summaryrefslogtreecommitdiff
path: root/controller/fw/tools/freq_meas_test.c
blob: 01b49630cf2c84d3ac82b7b3a2914adcdfc8a425 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/fcntl.h>

#include "freq_meas.h"

void print_usage(void);

void print_usage() {
    fprintf(stderr, "Usage: freq_meas_test [test_data.bin]");
}

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "Error: Invalid arguments.\n");
        print_usage();
        return 1;
    }

    int fd = open(argv[1], O_RDONLY);
    struct stat st;
    if (fstat(fd, &st)) {
        fprintf(stderr, "Error querying test data file size: %s\n", strerror(errno));
        return 2;
    }

    if (st.st_size < 0 || st.st_size > 1000000) {
        fprintf(stderr, "Error reading test data: too much test data (size=%zd)\n", st.st_size);
        return 2;
    }

    if (st.st_size % sizeof(float) != 0) {
        fprintf(stderr, "Error reading test data: file size is not divisible by %zd (size=%zd)\n", sizeof(float), st.st_size);
        return 2;
    }

    char *buf = malloc(st.st_size);
    if (!buf) {
        fprintf(stderr, "Error allocating memory");
        return 2;
    }

    size_t nread = 0;
    while (nread < st.st_size) {
        ssize_t rc = read(fd, buf, st.st_size - nread);

        if (rc == -EINTR || rc == -EAGAIN)
            continue;

        if (rc < 0) {
            fprintf(stderr, "Error reading test data: %s\n", strerror(errno));
            return 2;
        }
        
        if (rc == 0) {
            fprintf(stderr, "Error reading test data: Unexpected end of file\n");
            return 2;
        }

        nread += rc;
    }

    size_t n_samples = st.st_size / sizeof(float);
    float *buf_f = (float *)buf;

    uint16_t *sim_adc_buf = calloc(sizeof(uint16_t), n_samples);
    if (!sim_adc_buf) {
        fprintf(stderr, "Error allocating memory\n");
        return 2;
    }

    for (size_t i=0; i<n_samples; i++)
        sim_adc_buf[i] = 2048 + buf_f[i] * 2047;

    for (size_t i=0; i<n_samples; i+=FMEAS_FFT_LEN) {

        float out;
        int rc = adc_buf_measure_freq(sim_adc_buf + i, &out);
        if (rc) {
            fprintf(stderr, "Simulation error in iteration %zd at position %zd: %d\n", i/FMEAS_FFT_LEN, i, rc);
            return 3;
        }

        printf("%09zd %015f\n", i, out);
    }

    return 0;
}