o_fwrite.cpp 1.97 KB
#include "blc_core.h"
#include "blc_channel.h"
#include "blc_program.h"
#include <unistd.h>
#include <termios.h>
#include <libgen.h> //basename

int main(int argc, char** argv){
    blc_channel channel;
    char const  *period_str;
    char const *channel_name, *filename, *time_str;
    char const *number_str;
    char const *ext;
    FILE *file;
    int number;
    int  period;
    struct timeval timer;
    

    blc_program_set_description("Write data of blc_channel");
    blc_program_add_option(&filename, 'f', "filename", "filename", "Filename of the file to record", NULL);
    blc_program_add_option(&number_str, 'n', "number", "integer", "Number of records (-1 for infinity)", "-1");
    blc_program_add_option(&period_str, 'p', "period", "integer", "Period in ms to read line by line", "0");
    blc_program_add_option(&time_str, 'T',  "time", NULL, "record time in first column (ansolute in µs)", NULL);
    blc_program_add_parameter(&channel_name, "blc_channel-in", 1, "channel to save", NULL);
    blc_program_init(&argc, &argv, blc_quit);
    blc_command_forward_blc_channels();

    if (filename==NULL) EXIT_ON_ERROR("You need to specify a file -f<name>.tsv");
    ext=blc_get_filename_extension(filename);
    if (strcmp(ext, "tsv")!=0)  EXIT_ON_ERROR("'%s' does not .tsv extension but '%s'", filename, ext); //This is to avoid accidental overwriting
    period=strtol(period_str, NULL,10)*1000;
    number=strtol(number_str, NULL,10);
    
    channel.open(channel_name, BLC_CHANNEL_READ);
    blc_loop_try_add_waiting_semaphore(channel.sem_new_data);
    blc_loop_try_add_posting_semaphore(channel.sem_ack_data);

    SYSTEM_ERROR_CHECK(file=fopen(filename, "w"), NULL, "Creating '%s'", filename);
    
    BLC_COMMAND_LOOP(period){
        if (time_str) fprintf(file, "%lld\t", (int64_t)blc_loop_timer.tv_sec*1000000+ (int64_t)blc_loop_timer.tv_usec);
        channel.fprint_tsv(file);
    }
    SYSTEM_ERROR_CHECK(fclose(file), -1, "Closing '%s'", filename);
    
    return EXIT_SUCCESS;
}