// // Written for Computer Networks and Systems lab classes // AUTHOR : Sergiusz Warga #include #include #include #include #include #include #include #include #include "CircBuffer.h" #include "funs.h" void handle_arguments(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s SAMPLING_FREQUENCY REFRESHING_FREQUENCY\n", argv[0]); exit(EXIT_FAILURE); } if (strtol(argv[1], NULL, 10) < 2) { fprintf(stderr, "Sampling frequency should be at least 400Hz!\n"); exit(EXIT_FAILURE); } if (strtol(argv[2], NULL, 10) > 1 || strtod(argv[2], NULL) < 0) { fprintf(stderr, "Refreshing frequency should be at least 1Hz!\n"); exit(EXIT_FAILURE); } } int crosses_zero(double prev, double curr) { // let's just ignore 0 for now return (prev > 0 && curr < 0) || (prev < 0 && curr > 0); } _Noreturn void k_f0(int fd, int sampling_frequency, int refreshing_frequency) { printf("A k_f0 has been called\n"); //----- Initialize the buffer ----- struct CircBuffer *buffer; buffer = mmap(NULL, sizeof(struct CircBuffer), PROT_READ, MAP_SHARED, fd, 0); if (buffer == MAP_FAILED) { fprintf(stderr, "mmap: "); exit(EXIT_FAILURE); } struct timespec tic, toc; unsigned long long delay = NSEC_PER_SEC*1./refreshing_frequency; clock_gettime(CLOCK_REALTIME, &tic); int transitions = 0; int samples = 0; int read_idx; read_idx = buffer->info.free_idx - 1; while (1) { clock_gettime(CLOCK_REALTIME, &toc); if (timespec_diff_nano(&toc, &tic) > delay) { double t_samp = 1./sampling_frequency; // printf("t_samp = %fs\n", t_samp); // printf("n_samp = %d\n", samples); double t_anal = t_samp*samples; // printf("t_anal = %fs\n", t_anal); // printf("n_tran = %d\n", transitions); printf("f = %fHz\n", transitions/(2*t_anal)); transitions = 0; samples = 0; clock_gettime(CLOCK_REALTIME, &tic); } if (crosses_zero(buffer->data[read_idx-1], buffer->data[read_idx])) { ++transitions; } while (read_idx == ((buffer->info.free_idx - 1) % buffer->info.size)) {}; read_idx = ++read_idx % buffer->info.size; ++samples; } } int main(int argc, char *argv[]) { handle_arguments(argc, argv); //----- Open a shared memory ----- const char *memory_name = "/dsp"; int fd = shm_open(memory_name, O_RDONLY, 0777); if (fd < 0) { fprintf(stderr, "shm_open: "); exit(EXIT_FAILURE); } printf("Shared memory file descriptor: %d\n", fd); k_f0(fd, strtol(argv[1], NULL, 10), strtol(argv[2], NULL, 10)); return 0; }