Exemplo n.º 1
0
int main(int argc, char *argv[]) {
    int n, i, c, count = 0, sample = 0, chan = 0, status = 0, verbose = 0, labelSize;
    unsigned char buf[OPENBCI_BUFLEN], byte;
    char *labelString;
    SerialPort SP;
    host_t host;
    struct timespec tic, toc;

    /* these represent the general acquisition system properties */
    int nchans         = OPENBCI_NCHANS;
    float fsample      = OPENBCI_FSAMPLE;

    /* these are used in the communication with the FT buffer and represent statefull information */
    int ftSocket           = -1;
    ft_buffer_server_t *ftServer;
    message_t     *request  = NULL;
    message_t     *response = NULL;
    header_t      *header   = NULL;
    data_t        *data     = NULL;
    ft_chunkdef_t *label    = NULL;

    /* this contains the configuration details */
    configuration config;

    /* configure the default settings */
    config.blocksize     = 10;
    config.port          = 1972;
    config.hostname      = strdup("-");
    config.serial        = strdup("/dev/tty.usbserial-DN0094FY");
    config.reset         = strdup("on");
    config.datalog       = strdup("off");
    config.testsignal    = strdup("off");
    config.timestamp     = strdup("on");
    config.timeref       = strdup("start");

    config.enable_chan1  = strdup("on");
    config.enable_chan2  = strdup("on");
    config.enable_chan3  = strdup("on");
    config.enable_chan4  = strdup("on");
    config.enable_chan5  = strdup("on");
    config.enable_chan6  = strdup("on");
    config.enable_chan7  = strdup("on");
    config.enable_chan8  = strdup("on");
    config.enable_chan9  = strdup("on");
    config.enable_chan10 = strdup("on");
    config.enable_chan11 = strdup("on");

    config.label_chan1  = strdup("ADC1");
    config.label_chan2  = strdup("ADC2");
    config.label_chan3  = strdup("ADC3");
    config.label_chan4  = strdup("ADC4");
    config.label_chan5  = strdup("ADC5");
    config.label_chan6  = strdup("ADC6");
    config.label_chan7  = strdup("ADC7");
    config.label_chan8  = strdup("ADC8");
    config.label_chan9  = strdup("AccelerationX");
    config.label_chan10 = strdup("AccelerationY");
    config.label_chan11 = strdup("AccelerationZ");
    config.label_chan12 = strdup("TimeStamp");

    config.setting_chan1  = strdup("x1060110X");
    config.setting_chan2  = strdup("x2060110X");
    config.setting_chan3  = strdup("x3060110X");
    config.setting_chan4  = strdup("x4060110X");
    config.setting_chan5  = strdup("x5060110X");
    config.setting_chan6  = strdup("x6060110X");
    config.setting_chan7  = strdup("x7060110X");
    config.setting_chan8  = strdup("x8060110X");

    config.impedance_chan1  = strdup("z100Z");
    config.impedance_chan2  = strdup("z200Z");
    config.impedance_chan3  = strdup("z300Z");
    config.impedance_chan4  = strdup("z400Z");
    config.impedance_chan5  = strdup("z500Z");
    config.impedance_chan6  = strdup("z600Z");
    config.impedance_chan7  = strdup("z700Z");
    config.impedance_chan8  = strdup("z800Z");

    if (argc<2) {
        printf(usage);
        exit(0);
    }

    if (argc==2) {
        if (strncmp(argv[1], "/dev", 4)==0 || strncasecmp(argv[1], "COM", 3)==0)
            /* the second argument is the serial port */
            config.serial = strdup(argv[1]);
        else {
            /* the second argument is the configuration file */
            fprintf(stderr, "openbci2ft: loading configuration from '%s'\n", argv[1]);
            if (ini_parse(argv[1], iniHandler, &config) < 0) {
                fprintf(stderr, "Can't load '%s'\n", argv[1]);
                return 1;
            }
        }
    }

    if (argc>2)
        strcpy(host.name, argv[2]);
    else {
        strcpy(host.name, config.hostname);
    }

    if (argc>3)
        host.port = atoi(argv[3]);
    else {
        host.port = config.port;
    }

#define ISTRUE(s) strcasecmp(s, "on")==0
    nchans = 0;
    if (ISTRUE(config.enable_chan1))
        nchans++;
    if (ISTRUE(config.enable_chan2))
        nchans++;
    if (ISTRUE(config.enable_chan3))
        nchans++;
    if (ISTRUE(config.enable_chan4))
        nchans++;
    if (ISTRUE(config.enable_chan5))
        nchans++;
    if (ISTRUE(config.enable_chan6))
        nchans++;
    if (ISTRUE(config.enable_chan7))
        nchans++;
    if (ISTRUE(config.enable_chan8))
        nchans++;
    if (ISTRUE(config.enable_chan9))
        nchans++;
    if (ISTRUE(config.enable_chan10))
        nchans++;
    if (ISTRUE(config.enable_chan11))
        nchans++;
    if (ISTRUE(config.timestamp))
        nchans++;

    fprintf(stderr, "openbci2ft: serial       =  %s\n", config.serial);
    fprintf(stderr, "openbci2ft: hostname     =  %s\n", host.name);
    fprintf(stderr, "openbci2ft: port         =  %d\n", host.port);
    fprintf(stderr, "openbci2ft: blocksize    =  %d\n", config.blocksize);
    fprintf(stderr, "openbci2ft: reset        =  %s\n", config.reset);
    fprintf(stderr, "openbci2ft: datalog      =  %s\n", config.datalog);
    fprintf(stderr, "openbci2ft: timestamp    =  %s\n", config.timestamp);
    fprintf(stderr, "openbci2ft: testsignal   =  %s\n", config.testsignal);

    /* Spawn tcpserver or connect to remote buffer */
    if (strcmp(host.name, "-") == 0) {
        ftServer = ft_start_buffer_server(host.port, NULL, NULL, NULL);
        if (ftServer==NULL) {
            fprintf(stderr, "openbci2ft: could not start up a local buffer serving at port %i\n", host.port);
            return 1;
        }
        ftSocket = 0;
        printf("openbci2ft: streaming to local buffer on port %i\n", host.port);
    }
    else {
        ftSocket = open_connection(host.name, host.port);

        if (ftSocket < 0) {
            fprintf(stderr, "openbci2ft: could not connect to remote buffer at %s:%i\n", host.name, host.port);
            return 1;
        }
        printf("openbci2ft: streaming to remote buffer at %s:%i\n", host.name, host.port);
    }

    /* allocate the elements that will be used in the communication to the FT buffer */
    request      = malloc(sizeof(message_t));
    request->def = malloc(sizeof(messagedef_t));
    request->buf = NULL;
    request->def->version = VERSION;
    request->def->bufsize = 0;

    header      = malloc(sizeof(header_t));
    header->def = malloc(sizeof(headerdef_t));
    header->buf = NULL;

    data      = malloc(sizeof(data_t));
    data->def = malloc(sizeof(datadef_t));
    data->buf = NULL;

    /* define the header */
    header->def->nchans    = nchans;
    header->def->fsample   = fsample;
    header->def->nsamples  = 0;
    header->def->nevents   = 0;
    header->def->data_type = DATATYPE_FLOAT32;
    header->def->bufsize   = 0;

    /* FIXME add the channel names */
    labelSize = 0; /* count the number of bytes required */
    if (ISTRUE (config.enable_chan1))
        labelSize += strlen (config.label_chan1) + 1;
    if (ISTRUE (config.enable_chan2))
        labelSize += strlen (config.label_chan2) + 1;
    if (ISTRUE (config.enable_chan3))
        labelSize += strlen (config.label_chan3) + 1;
    if (ISTRUE (config.enable_chan4))
        labelSize += strlen (config.label_chan4) + 1;
    if (ISTRUE (config.enable_chan5))
        labelSize += strlen (config.label_chan5) + 1;
    if (ISTRUE (config.enable_chan6))
        labelSize += strlen (config.label_chan6) + 1;
    if (ISTRUE (config.enable_chan7))
        labelSize += strlen (config.label_chan7) + 1;
    if (ISTRUE (config.enable_chan8))
        labelSize += strlen (config.label_chan8) + 1;
    if (ISTRUE (config.enable_chan9))
        labelSize += strlen (config.label_chan9) + 1;
    if (ISTRUE (config.enable_chan10))
        labelSize += strlen (config.label_chan10) + 1;
    if (ISTRUE (config.enable_chan11))
        labelSize += strlen (config.label_chan11) + 1;
    if (ISTRUE (config.timestamp))
        labelSize += strlen (config.label_chan12) + 1;

    if (verbose > 0)
        fprintf (stderr, "openbci2ft: labelSize = %d\n", labelSize);

    /* go over all channels for a 2nd time, now copying the strings to the destination */
    labelString = (char *) malloc (labelSize * sizeof(char));
    labelSize   = 0; 
    if (ISTRUE (config.enable_chan1)) {
        strcpy (labelString+labelSize, config.label_chan1);
        labelSize += strlen (config.label_chan1) + 1;
    }
    if (ISTRUE (config.enable_chan2)) {
        strcpy (labelString+labelSize, config.label_chan2);
        labelSize += strlen (config.label_chan2) + 1;
    }
    if (ISTRUE (config.enable_chan3)) {
        strcpy (labelString+labelSize, config.label_chan3);
        labelSize += strlen (config.label_chan3) + 1;
    }
    if (ISTRUE (config.enable_chan4)) {
        strcpy (labelString+labelSize, config.label_chan4);
        labelSize += strlen (config.label_chan4) + 1;
    }
    if (ISTRUE (config.enable_chan5)) {
        strcpy (labelString+labelSize, config.label_chan5);
        labelSize += strlen (config.label_chan5) + 1;
    }
    if (ISTRUE (config.enable_chan6)) {
        strcpy (labelString+labelSize, config.label_chan6);
        labelSize += strlen (config.label_chan6) + 1;
    }
    if (ISTRUE (config.enable_chan7)) {
        strcpy (labelString+labelSize, config.label_chan7);
        labelSize += strlen (config.label_chan7) + 1;
    }
    if (ISTRUE (config.enable_chan8)) {
        strcpy (labelString+labelSize, config.label_chan8);
        labelSize += strlen (config.label_chan8) + 1;
    }
    if (ISTRUE (config.enable_chan9)) {
        strcpy (labelString+labelSize, config.label_chan9);
        labelSize += strlen (config.label_chan9) + 1;
    }
    if (ISTRUE (config.enable_chan10)) {
        strcpy (labelString+labelSize, config.label_chan10);
        labelSize += strlen (config.label_chan10) + 1;
    }
    if (ISTRUE (config.enable_chan11)) {
        strcpy (labelString+labelSize, config.label_chan11);
        labelSize += strlen (config.label_chan11) + 1;
    }
    if (ISTRUE (config.timestamp)) {
        strcpy (labelString+labelSize, config.label_chan12);
        labelSize += strlen (config.label_chan12) + 1;
    }

    /* add the channel label chunk to the header */
    label = (ft_chunkdef_t *) malloc (sizeof (ft_chunkdef_t));
    label->type = FT_CHUNK_CHANNEL_NAMES;
    label->size = labelSize;
    header->def->bufsize = append (&header->buf, header->def->bufsize, label, sizeof (ft_chunkdef_t));
    header->def->bufsize = append (&header->buf, header->def->bufsize, labelString, labelSize);
    FREE (label);
    FREE (labelString);

    /* define the constant part of the data and allocate space for the variable part */
    data->def->nchans = nchans;
    data->def->nsamples = config.blocksize;
    data->def->data_type = DATATYPE_FLOAT32;
    data->def->bufsize = WORDSIZE_FLOAT32 * nchans * config.blocksize;
    data->buf = malloc (data->def->bufsize);

    /* initialization phase, send the header */
    request->def->command = PUT_HDR;
    request->def->bufsize = append (&request->buf, request->def->bufsize, header->def, sizeof (headerdef_t));
    request->def->bufsize = append (&request->buf, request->def->bufsize, header->buf, header->def->bufsize);

    /* this is not needed any more */
    cleanup_header (&header);

    status = clientrequest (ftSocket, request, &response);
    if (verbose > 0)
        fprintf (stderr, "openbci2ft: clientrequest returned %d\n", status);
    if (status)
    {
        fprintf (stderr, "openbci2ft: could not send request to buffer\n");
        exit (1);
    }

    if (status || response == NULL || response->def == NULL)
    {
        fprintf (stderr, "openbci2ft: error in %s on line %d\n", __FILE__,
                __LINE__);
        exit (1);
    }

    cleanup_message (&request);

    if (response->def->command != PUT_OK)
    {
        fprintf (stderr, "openbci2ft: error in 'put header' request.\n");
        exit (1);
    }

    cleanup_message (&response);

    /* open the serial port */
    fprintf (stderr, "openbci2ft: opening serial port ...\n");
    if (!serialOpenByName (&SP, config.serial))
    {
        fprintf (stderr, "Could not open serial port %s\n", config.serial);
        return 1;
    }

    if (!serialSetParameters (&SP, 115200, 8, 0, 0, 0))
    {
        fprintf (stderr, "Could not modify serial port parameters\n");
        return 1;
    }

    fprintf (stderr, "openbci2ft: opening serial port ... ok\n");

    /* 8-bit board will always be initialized upon opening serial port, 32-bit board needs explicit initialization */

    fprintf (stderr, "openbci2ft: initializing ...\n");
    fprintf (stderr,
            "openbci2ft: press reset on the OpenBCI board if this takes too long\n");

    if (ISTRUE (config.reset))
        serialWrite (&SP, 1, "v");	/* soft reset, this will return $$$ */
    else
        serialWrite (&SP, 1, "D");	/* query default channel settings, this will also return $$$ */

    /* wait for '$$$' which indicates that the OpenBCI has been initialized */
    c = 0;
    while (c != 3)
    {
        usleep (1000);
        n = serialRead (&SP, 1, &byte);
        if (n == 1)
        {
            if (byte == '$')
                c++;
            else
                c = 0;
        }
    }				/* while waiting for '$$$' */

    if (strcasecmp (config.datalog, "14s") == 0)
        serialWrite (&SP, 1, "a");
    else if (strcasecmp (config.datalog, "5min") == 0)
        serialWrite (&SP, 1, "A");
    else if (strcasecmp (config.datalog, "15min") == 0)
        serialWrite (&SP, 1, "S");
    else if (strcasecmp (config.datalog, "30min") == 0)
        serialWrite (&SP, 1, "F");
    else if (strcasecmp (config.datalog, "1hr") == 0)
        serialWrite (&SP, 1, "G");
    else if (strcasecmp (config.datalog, "2hr") == 0)
        serialWrite (&SP, 1, "H");
    else if (strcasecmp (config.datalog, "4hr") == 0)
        serialWrite (&SP, 1, "J");
    else if (strcasecmp (config.datalog, "12hr") == 0)
        serialWrite (&SP, 1, "K");
    else if (strcasecmp (config.datalog, "24hr") == 0)
        serialWrite (&SP, 1, "L");
    else if (strcasecmp (config.datalog, "off") != 0)
    {
        fprintf (stderr, "Incorrect specification of datalog\n");
        return 1;
    }

    serialWriteSlow (&SP, strlen (config.setting_chan1), config.setting_chan1);
    serialWriteSlow (&SP, strlen (config.setting_chan2), config.setting_chan2);
    serialWriteSlow (&SP, strlen (config.setting_chan3), config.setting_chan3);
    serialWriteSlow (&SP, strlen (config.setting_chan4), config.setting_chan4);
    serialWriteSlow (&SP, strlen (config.setting_chan5), config.setting_chan5);
    serialWriteSlow (&SP, strlen (config.setting_chan6), config.setting_chan6);
    serialWriteSlow (&SP, strlen (config.setting_chan7), config.setting_chan7);
    serialWriteSlow (&SP, strlen (config.setting_chan8), config.setting_chan8);

    if (strcasecmp (config.testsignal, "gnd") == 0)
        serialWrite (&SP, 1, "0");
    else if (strcasecmp (config.testsignal, "dc") == 0)
        serialWrite (&SP, 1, "-");
    else if (strcasecmp (config.testsignal, "1xSlow") == 0)
        serialWrite (&SP, 1, "=");
    else if (strcasecmp (config.testsignal, "1xFast") == 0)
        serialWrite (&SP, 1, "p");
    else if (strcasecmp (config.testsignal, "2xSlow") == 0)
        serialWrite (&SP, 1, "[");
    else if (strcasecmp (config.testsignal, "2xFast") == 0)
        serialWrite (&SP, 1, "]");
    else if (strcasecmp (config.testsignal, "off") != 0)
    {
        fprintf (stderr, "Incorrect specification of testsignal\n");
        return 1;
    }

    fprintf (stderr, "openbci2ft: initializing ... ok\n");

    printf ("Starting to listen - press CTRL-C to quit\n");

    /* register CTRL-C handler */
    signal (SIGINT, abortHandler);

    /* start streaming data */
    serialWrite (&SP, 1, "b");

    /* determine the reference time for the timestamps */
    if (strcasecmp (config.timeref, "start") == 0)
    {
        /* since the start of the acquisition */
        get_monotonic_time (&tic, TIMESTAMP_REF_BOOT);
    }
    else if (strcasecmp (config.timeref, "boot") == 0)
    {
        /* since the start of the day */
        tic.tv_sec = 0;
        tic.tv_nsec = 0;
    }
    else if (strcasecmp (config.timeref, "epoch") == 0)
    {
        /* since the start of the epoch, i.e. 1-1-1970 */
        tic.tv_sec = 0;
        tic.tv_nsec = 0;
    }
    else
    {
        fprintf (stderr,
                "Incorrect specification of timeref, should be 'start', 'day' or 'epoch'\n");
        return 1;
    }

    while (keepRunning)
    {

        sample = 0;
        while (sample < config.blocksize)
        {
            /* wait for the first byte of the following packet */
            buf[0] = 0;
            while (buf[0] != 0xA0)
            {
                if (serialInputPending (&SP))
                    n = serialRead (&SP, 1, buf);
                else
                    usleep (1000);
            }			/* while */

            /*
             * Header
             *   Byte 1: 0xA0
             *   Byte 2: Sample Number
             *
             * EEG Data
             * Note: values are 24-bit signed, MSB first
             *   Bytes 3-5: Data value for EEG channel 1
             *   Bytes 6-8: Data value for EEG channel 2
             *   Bytes 9-11: Data value for EEG channel 3
             *   Bytes 12-14: Data value for EEG channel 4
             *   Bytes 15-17: Data value for EEG channel 5
             *   Bytes 18-20: Data value for EEG channel 6
             *   Bytes 21-23: Data value for EEG channel 6
             *   Bytes 24-26: Data value for EEG channel 8
             *
             * Accelerometer Data
             * Note: values are 16-bit signed, MSB first
             *   Bytes 27-28: Data value for accelerometer channel X
             *   Bytes 29-30: Data value for accelerometer channel Y
             *   Bytes 31-32: Data value for accelerometer channel Z
             *
             * Footer
             *   Byte 33: 0xC0
             */

            /* read the remaining 32 bytes of the packet */
            while (n < OPENBCI_BUFLEN)
                if (serialInputPending (&SP))
                    n += serialRead (&SP, (OPENBCI_BUFLEN - n), buf + n);
                else
                    usleep (1000);

            if (verbose > 1)
            {
                for (i = 0; i < OPENBCI_BUFLEN; i++)
                    printf ("%02x ", buf[i]);
                printf ("\n");
            }

            chan = 0;
            if (ISTRUE (config.enable_chan1))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[2] << 24 | buf[3] << 16 | buf[4] << 8) /
                    255;
            if (ISTRUE (config.enable_chan2))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[5] << 24 | buf[6] << 16 | buf[7] << 8) /
                    255;
            if (ISTRUE (config.enable_chan3))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[8] << 24 | buf[9] << 16 | buf[10] << 8) /
                    255;
            if (ISTRUE (config.enable_chan4))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[11] << 24 | buf[12] << 16 | buf[13] << 8) /
                    255;
            if (ISTRUE (config.enable_chan5))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[14] << 24 | buf[15] << 16 | buf[16] << 8) /
                    255;
            if (ISTRUE (config.enable_chan6))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[17] << 24 | buf[18] << 16 | buf[19] << 8) /
                    255;
            if (ISTRUE (config.enable_chan7))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[20] << 24 | buf[21] << 16 | buf[22] << 8) /
                    255;
            if (ISTRUE (config.enable_chan8))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB1 * (buf[23] << 24 | buf[24] << 16 | buf[25] << 8) /
                    255;

            if (ISTRUE (config.enable_chan9))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB2 * (buf[26] << 24 | buf[27] << 16) / 32767;
            if (ISTRUE (config.enable_chan10))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB2 * (buf[28] << 24 | buf[29] << 16) / 32767;
            if (ISTRUE (config.enable_chan11))
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    OPENBCI_CALIB2 * (buf[28] << 24 | buf[31] << 16) / 32767;

            if (ISTRUE (config.timestamp))
            {
                if (strcasecmp (config.timeref, "start") == 0)
                    get_monotonic_time (&toc, TIMESTAMP_REF_BOOT);
                else if (strcasecmp (config.timeref, "boot") == 0)
                    get_monotonic_time (&toc, TIMESTAMP_REF_BOOT);
                else if (strcasecmp (config.timeref, "epoch") == 0)
                    get_monotonic_time (&toc, TIMESTAMP_REF_EPOCH);
                ((FLOAT32_T *) (data->buf))[nchans * sample + (chan++)] =
                    get_elapsed_time (&tic, &toc);
            }

            sample++;
        }				/* while c<config.blocksize */

        count += sample;
        printf ("openbci2ft: sample count = %i\n", count);

        /* create the request */
        request = malloc (sizeof (message_t));
        request->def = malloc (sizeof (messagedef_t));
        request->buf = NULL;
        request->def->version = VERSION;
        request->def->bufsize = 0;
        request->def->command = PUT_DAT;

        request->def->bufsize = append (&request->buf, request->def->bufsize, data->def, sizeof (datadef_t));
        request->def->bufsize = append (&request->buf, request->def->bufsize, data->buf, data->def->bufsize);

        status = clientrequest (ftSocket, request, &response);
        if (verbose > 0)
            fprintf (stderr, "openbci2ft: clientrequest returned %d\n", status);
        if (status)
        {
            fprintf (stderr, "openbci2ft: error in %s on line %d\n", __FILE__,
                    __LINE__);
            exit (1);
        }

        if (status)
        {
            fprintf (stderr, "openbci2ft: error in %s on line %d\n", __FILE__,
                    __LINE__);
            exit (1);
        }

        /* FIXME do someting with the response, i.e. check that it is OK */
        cleanup_message (&request);

        if (response == NULL || response->def == NULL
                || response->def->command != PUT_OK)
        {
            fprintf (stderr, "Error when writing samples.\n");
        }
        cleanup_message (&response);

    }				/* while keepRunning */

    /* stop streaming data */
    serialWrite (&SP, 1, "s");

    cleanup_data (&data);

    if (ftSocket > 0)
    {
        close_connection (ftSocket);
    }
    else
    {
        ft_stop_buffer_server (ftServer);
    }

    return 0;
}				/* main */
Exemplo n.º 2
0
/* this function deals with the incoming client request */
void *tcpsocket(void *arg) {
	int n;
	int status = 0, verbose = 0;
	int oldcancelstate, oldcanceltype;

#ifdef ENABLE_POLLING
	struct pollfd fds;
#endif

	// these are used for communication over the TCP socket
	int client = 0;
	message_t *request = NULL, *response = NULL;

	/* the connection to the client has been made by the server */
	client = (int)arg;

    /* this is for debugging */
    pthread_mutex_lock(&mutexsocketcount);
    socketcount++;
    pthread_mutex_unlock(&mutexsocketcount);

	/* this is to prevent closing the thread at an unwanted moment and memory from leaking */
	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldcancelstate);
	pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldcanceltype);
	pthread_cleanup_push(cleanup_message, &request);
	pthread_cleanup_push(cleanup_message, &response)
	pthread_cleanup_push(cleanup_socket, &client);

    if (verbose>1) fprintf(stderr, "tcpsocket: client = %d, socketcount = %d, threadcount = %d\n", client, socketcount, threadcount);

	/* keep processing messages untill the connection is closed */
	while (1) {

	request       = (message_t*)malloc(sizeof(message_t));
	request->def  = (messagedef_t*)malloc(sizeof(messagedef_t));
	request->buf  = NULL;

#ifdef ENABLE_POLLING
		/* wait for data to become available or until the connection is closed */
		/* thohar: i think this is not neccessary as we dont need a timeout. */
		/* roboos: we need it to detect when the socket is closed by the client */
		while (1) {
			fds.fd      = client;
			fds.events  = POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI | POLLOUT | POLLWRNORM | POLLWRBAND | POLLERR | POLLNVAL;
			fds.revents = 0;

			if (poll(&fds, 1, 1)==-1) {
				perror("poll");
				goto cleanup;
			}

			if (fds.revents & POLLHUP)
				goto cleanup;				// the connection has been closed
			else if (fds.revents & POLLERR)
				goto cleanup;				// the connection has been closed
			else if (fds.revents & POLLIN)
				break;						// data is available, process the message
			else
				usleep(POLLSLEEP);			// wait for data or closed connection
		}
#endif

		if ((n = bufread(client, request->def, sizeof(messagedef_t))) != sizeof(messagedef_t)) {
			if (verbose>0) fprintf(stderr, "tcpsocket: packet size = %d, should be %d\n", n, sizeof(messagedef_t));
			goto cleanup;
		}

		if (request->def->version!=VERSION) {
			if (verbose>0) fprintf(stderr, "tcpsocket: incorrect request version\n");
			goto cleanup;
		}

		if (request->def->bufsize>0) {
			request->buf = malloc(request->def->bufsize);
			if ((n = bufread(client, request->buf, request->def->bufsize)) != request->def->bufsize) {
				if (verbose>0) fprintf(stderr, "tcpsocket: read size = %d, should be %d\n", n, request->def->bufsize);
				goto cleanup;
			}
		}

		if (verbose>1) print_request(request->def);
		if (verbose>1) print_buf(request->buf, request->def->bufsize);

		if ((status = dmarequest(request, &response)) != 0) {
			if (verbose>0) fprintf(stderr, "tcpsocket: an unexpected error occurred\n");
			goto cleanup;
		}

		if (verbose>1) print_response(response->def);
		if (verbose>1) print_buf(request->buf, request->def->bufsize);

		if ((n = bufwrite(client, response->def, sizeof(messagedef_t)))!=sizeof(messagedef_t)) {
			if (verbose>0) fprintf(stderr, "tcpsocket: write size = %d, should be %d\n", n, sizeof(messagedef_t));
			goto cleanup;
		}
		if ((n = bufwrite(client, response->buf, response->def->bufsize))!=response->def->bufsize) {
			if (verbose>0) fprintf(stderr, "tcpsocket: write size = %d, should be %d\n", n, response->def->bufsize);
			goto cleanup;
		}

		cleanup_message(&request);
		cleanup_message(&response);
        request = NULL;
        response = NULL;

	} /* while (1) */

cleanup:
	/* from now on it is safe to cancel the thread */
	pthread_setcancelstate(oldcancelstate, NULL);
	pthread_setcanceltype(oldcanceltype, NULL);

	pthread_cleanup_pop(1); // request
	pthread_cleanup_pop(1); // response
	pthread_cleanup_pop(1); // socket

    /* this is for debugging */
    pthread_mutex_lock(&mutexsocketcount);
    socketcount--;
    pthread_mutex_unlock(&mutexsocketcount);

    /* this is for debugging */
    pthread_mutex_lock(&mutexthreadcount);
    threadcount--;
    pthread_mutex_unlock(&mutexthreadcount);

	pthread_exit(NULL);
	return NULL;
}
Exemplo n.º 3
0
/** Background thread for grabbing setup and data packets from the internal, overallocated ringbuffer.
    This thread stops automatically if the socket pair is closed in the main thread.
*/
void *dataToFieldTripThread(void *arg) {
	ACQ_OverAllocType *pack;
	EventChain EC;
	int slot, res, i,j;
	int numChannels = 0, numSamples;
	int warningGiven = 0;
	messagedef_t reqdef;
	message_t request, *response;
	
	EC.evs = NULL;
	EC.sizeAlloc = 0;
	
	request.def = &reqdef;
	
	while (1) {
		res = read(mySockets[1], &slot, sizeof(int));
		
		if (res == 0) break; /* socket pair was closed - exit */
		
		if (res != sizeof(int)) {
			fprintf(stderr, "Error when reading from socket pair\n");
			break;
		}
		
		if (slot<0 || slot>=INT_RB_SIZE) {
			fprintf(stderr, "Got errorneous slot number from socket pair\n");
			break;
		}
		
		pack = &intPackets[slot];
		
		if (pack->message_type == ACQ_MSGQ_SETUP_COLLECTION) {
			UINT32_T size;
			headerdef_t *hdef;	/* contains header information + chunks !!! */
			
			hdef = handleRes4((const char *) pack->data, &size);
			/* clear internal ringbuffer slot */
			pack->message_type = ACQ_MSGQ_INVALID;
			
			if (hdef == NULL) continue;	/* problem while picking up header -- ignore this packet */
			
			/* prepare PUT_HDR request here, but only send it along with first data block */
			reqdef.version = VERSION;
			reqdef.command = PUT_HDR;
			reqdef.bufsize = size;
			request.buf = hdef;
				
			res = clientrequest(ftSocket, &request, &response);
				
			if (res < 0) {
				fprintf(stderr, "Error in FieldTrip connection\n");
			} else if (response) {
				if (response->def->command != PUT_OK) {
					fprintf(stderr, "Error in PUT_HDR\n");
				} else {
					/* printf("FT: Transmitted header\n"); */
					
					/* set numChannels variable to the value we picked up
					   this also enables transmitting data in following packets
					*/
					numChannels = hdef->nchans;
					warningGiven = 0;
				}
				cleanup_message((void **) &response);
			}
			free(hdef);
			
		} else if (pack->message_type == ACQ_MSGQ_DATA) {
			datadef_t *ddef; 
			int sampleNumber;
			
			if (numChannels == 0) {
				fprintf(stderr, "No header written yet -- ignoring data packet\n");
				pack->message_type = ACQ_MSGQ_INVALID;
				continue;
			}
			
			if (!warningGiven && pack->numChannels != numChannels) {
				printf("\nWARNING: Channel count in first data packet does not equal header information from .res4 file (%i channels)\n\n", numChannels);
				warningGiven = 1;
			}
			
			sampleNumber = pack->sampleNumber;
			numSamples   = pack->numSamples;
			
			/* Put the FT datadef at the location of the current ACQ packet definition.
			   This just fits, no memcpy'ing of the samples again... */
			ddef = (datadef_t *) &pack->messageId; 
			
			ddef->nsamples = numSamples;
			ddef->nchans = numChannels;
			ddef->data_type = DATATYPE_INT32;
			ddef->bufsize = sizeof(int) * numSamples * numChannels;
			
			reqdef.version = VERSION;
			reqdef.command = PUT_DAT;
			reqdef.bufsize = ddef->bufsize + sizeof(datadef_t);
			request.buf = ddef; /* data is still behind that */
			
			res = clientrequest(ftSocket, &request, &response);
			
			if (res < 0) {
				fprintf(stderr, "Error in FieldTrip connection (writing data)\n");
			} else if (response) {
				if (response->def->command != PUT_OK) {
					fprintf(stderr, "Error in PUT_DAT\n");
				} else {
					/* printf("FT: Transmitted samples\n"); */
				}
				cleanup_message((void **) &response);
			}
			
			/* look at trigger channels and add events to chain, clear this first */
			EC.size = EC.num = 0;
			for (j=0;j<numSamples;j++) {
				int *sj = pack->data + j*numChannels;
				for (i=0;i<numTriggerChannels;i++) {
					int sji = sj[triggerChannel[i]];
					if (sji != lastValue[i] && sji > 0) addTriggerEvent(&EC, i, sampleNumber + j, sji);
					lastValue[i] = sji;
				}
			}
			if (EC.size > 0) {
				reqdef.version = VERSION;
				reqdef.command = PUT_EVT;
				reqdef.bufsize = EC.size;
				request.buf = EC.evs;
				
				res = clientrequest(ftSocket, &request, &response);
			
				if (res < 0) {
					fprintf(stderr, "Error in FieldTrip connection (writing events)\n");
				} else if (response) {
					if (response->def->command != PUT_OK) {
						fprintf(stderr, "Error in PUT_EVT\n");
					} else {
						printf("Wrote %i events (%i bytes)\n", EC.num, reqdef.bufsize);
						/* printf("FT: Transmitted samples\n"); */
					}
				}
				cleanup_message((void **) &response);
			}
		} else {
			fprintf(stderr,"Converter thread: Packet contains neither SETUP nor DATA (%i)...\n", pack->message_type);
		}
		pack->message_type = ACQ_MSGQ_INVALID;
	}
	printf("Leaving converter thread...\n");
	close(mySockets[1]);
	if (EC.sizeAlloc > 0) free(EC.evs);
	return NULL;
}
Exemplo n.º 4
0
/* this function deals with the incoming client request */
void *tcpsocket(void *arg) {
	int n;
	int status = 0, verbose = 0;
	int oldcancelstate, oldcanceltype;

#ifdef ENABLE_POLLING
	struct pollfd fds;
#endif

	/* these are used for communication over the TCP socket */
	int client = 0;
	message_t *request = NULL, *response = NULL;

    threadlocal_t threadlocal;
    threadlocal.message = NULL;
    threadlocal.fd = -1;

	/* the connection to the client has been made by the server */
	client = (int)arg;

    /* this will be closed at cleanup */
    threadlocal.fd = client;

    pthread_cleanup_push(cleanup_tcpsocket, &threadlocal);

    /* this is for debugging */
    pthread_mutex_lock(&mutexsocketcount);
    socketcount++;
    pthread_mutex_unlock(&mutexsocketcount);

    if (verbose>1) fprintf(stderr, "tcpsocket: client = %d, socketcount = %d, threadcount = %d\n", client, socketcount, threadcount);

	/* keep processing messages untill the connection is closed */
	while (1) {
		int swap = 0;
		UINT16_T reqCommand;
		UINT32_T respBufSize;

		request       = (message_t*)malloc(sizeof(message_t));
		DIE_BAD_MALLOC(request);
		
		request->def  = (messagedef_t*)malloc(sizeof(messagedef_t));
		DIE_BAD_MALLOC(request->def);
		request->buf  = NULL;

#ifdef ENABLE_POLLING
		/* wait for data to become available or until the connection is closed */
		/* thohar: i think this is not neccessary as we dont need a timeout. */
		/* roboos: we need it to detect when the socket is closed by the client */
		while (1) {
			fds.fd      = client;
			fds.events  = POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI | POLLOUT | POLLWRNORM | POLLWRBAND | POLLERR | POLLNVAL;
			fds.revents = 0;

			if (poll(&fds, 1, 1)==-1) {
				perror("poll");
				goto cleanup;
			}

			if (fds.revents & POLLHUP)
				goto cleanup;				/* the connection has been closed */
			else if (fds.revents & POLLERR)
				goto cleanup;				/* the connection has been closed */
			else if (fds.revents & POLLIN)
				break;						/* data is available, process the message */
			else
				usleep(POLLSLEEP);			/* wait for data or closed connection */
		}
#endif

		if ((n = bufread(client, request->def, sizeof(messagedef_t))) != sizeof(messagedef_t)) {
			if (verbose>0) fprintf(stderr, "tcpsocket: packet size = %d, should be %d\n", n, sizeof(messagedef_t));
			goto cleanup;
		}
		
		if (request->def->version==VERSION_OE) {
			swap = 1;
			ft_swap16(2, &request->def->version); /* version + command */
			ft_swap32(1, &request->def->bufsize);
			reqCommand = request->def->command;		
		}

		if (request->def->version!=VERSION) {
			if (verbose>0) fprintf(stderr, "tcpsocket: incorrect request version\n");
			goto cleanup;
		}
		
		if (request->def->bufsize>0) {
			request->buf = malloc(request->def->bufsize);
			DIE_BAD_MALLOC(request->buf);
			if ((n = bufread(client, request->buf, request->def->bufsize)) != request->def->bufsize) {
				if (verbose>0) fprintf(stderr, "tcpsocket: read size = %d, should be %d\n", n, request->def->bufsize);
				goto cleanup;
			}
		}
		
		if (swap && request->def->bufsize > 0) ft_swap_buf_to_native(reqCommand, request->def->bufsize, request->buf);

		if (verbose>1) print_request(request->def);
		if (verbose>1) print_buf(request->buf, request->def->bufsize);

		if ((status = dmarequest(request, &response)) != 0) {
			if (verbose>0) fprintf(stderr, "tcpsocket: an unexpected error occurred\n");
			goto cleanup;
		}
		
		DIE_BAD_MALLOC(response);
		DIE_BAD_MALLOC(response->def);
		
		if (verbose>1) print_response(response->def);
		if (verbose>1) print_buf(request->buf, request->def->bufsize);
		
		respBufSize = response->def->bufsize;
		if (swap) ft_swap_from_native(reqCommand, response);

		/* we don't need the request anymore */
		cleanup_message((void**)&request);
		request = NULL;
		
		/* merge response->def and response->buf if they are small, so we can send it in one go over TCP */
		if (respBufSize + sizeof(messagedef_t) <= MERGE_THRESHOLD) {
			int msize = respBufSize + sizeof(messagedef_t);
			void *merged = NULL;
			
			append(&merged, 0, response->def, sizeof(messagedef_t));
			DIE_BAD_MALLOC(merged);
			append(&merged, sizeof(messagedef_t), response->buf, respBufSize);
			DIE_BAD_MALLOC(merged);
						
			if ((n=bufwrite(client, merged, msize) != msize)) {
				if (verbose>0) fprintf(stderr, "tcpsocket: write size = %d, should be %d\n", n, msize);
				FREE(merged);
				goto cleanup;
			}
			FREE(merged);
		} else {
			if ((n = bufwrite(client, response->def, sizeof(messagedef_t)))!=sizeof(messagedef_t)) {
				if (verbose>0) fprintf(stderr, "tcpsocket: write size = %d, should be %d\n", n, sizeof(messagedef_t));
				goto cleanup;
			}
			if ((n = bufwrite(client, response->buf, respBufSize))!=respBufSize) {
				if (verbose>0) fprintf(stderr, "tcpsocket: write size = %d, should be %d\n", n, respBufSize);
				goto cleanup;
			}
		}

		cleanup_message((void**)&response);
        response = NULL;

	} /* while (1) */

cleanup:
    printf(""); /* otherwise the pthread_cleanup_pop won't compile */

	if (response!=NULL) 
		cleanup_message((void**)&response);
	response = NULL;	/* SK: prevent double free in following pthread_cleanup_pop */

	pthread_cleanup_pop(1);

    /* this is for debugging */
    pthread_mutex_lock(&mutexsocketcount);
    socketcount--;
    pthread_mutex_unlock(&mutexsocketcount);

    /* this is for debugging */
    pthread_mutex_lock(&mutexthreadcount);
    threadcount--;
    pthread_mutex_unlock(&mutexthreadcount);

	pthread_exit(NULL);
	return NULL;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
		int n, i, c, sample = 0, status = 0, verbose = 0;
		unsigned char buf[BUFLEN], byte;
		SerialPort SP;
		host_t host;

		/* these represent the acquisition system properties */
		int nchans         = OPENBCI_NCHANS;
		int blocksize      = BLOCKSIZE;
		float fsample      = OPENBCI_FSAMPLE;

		/* these are used in the communication with the FT buffer and represent statefull information */
		int ftSocket           = -1;
		ft_buffer_server_t *ftServer;
		message_t    *request  = NULL;
		message_t    *response = NULL;
		header_t     *header   = NULL;
		data_t       *data     = NULL;

		if (argc<2) {
				printf(usage);
				exit(0);
		}

		if (argc>2)
				strcpy(host.name, argv[2]);
		else {
				strcpy(host.name, FTHOST);
		}

		if (argc>3)
				host.port = atoi(argv[3]);
		else {
				host.port = FTPORT;
		}

		fprintf(stderr, "openbci2ft: device       =  %s\n", argv[1]);
		fprintf(stderr, "openbci2ft: hostname     =  %s\n", host.name);
		fprintf(stderr, "openbci2ft: port         =  %d\n", host.port);

		/* Spawn tcpserver or connect to remote buffer */
		if (strcmp(host.name, "-") == 0) {
				ftServer = ft_start_buffer_server(host.port, NULL, NULL, NULL);
				if (ftServer==NULL) {
						fprintf(stderr, "openbci2ft: could not start up a local buffer serving at port %i\n", host.port);
						return 1;
				}
				ftSocket = 0;
				printf("openbci2ft: streaming to local buffer on port %i\n", host.port);
		}
		else {
				ftSocket = open_connection(host.name, host.port);

				if (ftSocket < 0) {
						fprintf(stderr, "openbci2ft: could not connect to remote buffer at %s:%i\n", host.name, host.port);
						return 1;
				}
				printf("openbci2ft: streaming to remote buffer at %s:%i\n", host.name, host.port);
		}  

		/* allocate the elements that will be used in the communication to the FT buffer */
		request      = malloc(sizeof(message_t));
		request->def = malloc(sizeof(messagedef_t));
		request->buf = NULL;
		request->def->version = VERSION;
		request->def->bufsize = 0;

		header      = malloc(sizeof(header_t));
		header->def = malloc(sizeof(headerdef_t));
		header->buf = NULL;

		data      = malloc(sizeof(data_t));
		data->def = malloc(sizeof(datadef_t));
		data->buf = NULL;

		/* define the header */
		header->def->nchans    = nchans;
		header->def->fsample   = fsample;
		header->def->nsamples  = 0;
		header->def->nevents   = 0;
		header->def->data_type = DATATYPE_FLOAT32;
		header->def->bufsize   = 0;

		/* define the constant part of the data and allocate space for the variable part */
		data->def->nchans    = nchans;
		data->def->nsamples  = blocksize;
		data->def->data_type = DATATYPE_FLOAT32;
		data->def->bufsize   = WORDSIZE_FLOAT32*nchans*blocksize;
		data->buf            = malloc(data->def->bufsize);

		/* initialization phase, send the header */
		request->def->command = PUT_HDR;
		request->def->bufsize = append(&request->buf, request->def->bufsize, header->def, sizeof(headerdef_t));
		request->def->bufsize = append(&request->buf, request->def->bufsize, header->buf, header->def->bufsize);

		/* this is not needed any more */
		cleanup_header(&header);

		status = clientrequest(ftSocket, request, &response);
		if (verbose>0)
				fprintf(stderr, "openbci2ft: clientrequest returned %d\n", status);
		if (status) {
				fprintf(stderr, "openbci2ft: could not send request to buffer\n");
				exit(1);
		}

		if (status || response==NULL || response->def == NULL) {
				fprintf(stderr, "openbci2ft: error in %s on line %d\n", __FILE__, __LINE__);
				exit(1);
		}

		cleanup_message(&request);

		if (response->def->command != PUT_OK) {
				fprintf(stderr, "openbci2ft: error in 'put header' request.\n");
				exit(1);
		}

		cleanup_message(&response);

		/* open the serial port */
		fprintf(stderr, "openbci2ft: opening serial port ...\n");
		if (!serialOpenByName(&SP, argv[1])) {
				fprintf(stderr, "Could not open serial port %s\n", argv[1]);
				return 1;
		}

		if (!serialSetParameters(&SP, 115200, 8, 0, 0, 0)) {
				fprintf(stderr, "Could not modify serial port parameters\n");
				return 1;
		}

		fprintf(stderr, "openbci2ft: opening serial port ... ok\n");

		/* 8-bit board will always be initialized upon opening serial port, 32-bit board needs explicit initialization */
		fprintf(stderr, "openbci2ft: initializing ...\n");

		serialWrite(&SP, 1, "v");
		fprintf(stderr, "openbci2ft: press reset on the OpenBCI board if this takes too long\n");
		usleep(1000);

		/* wait for '$$$' which indicates that the OpenBCI has been initialized */
		c = 0;
		while (c!=3) {
				n = serialRead(&SP, 1, &byte);
				if (n==1) {
						if (byte=='$')
								c++;
						else
								c = 0;
				}
		} /* while waiting for '$$$' */

		fprintf(stderr, "openbci2ft: initializing ... ok\n");

		printf("Starting to listen - press CTRL-C to quit\n");

		/* register CTRL-C handler */
		signal(SIGINT, abortHandler);

		/* start streaming data */
		serialWrite(&SP, 1, "b");

		while (keepRunning) {

				c = 0;
				while (c<blocksize) {
						/* wait for the first byte of the packet */
						buf[0]=0;
						while (buf[0]!=0xA0) {
								if (serialInputPending(&SP))
										n = serialRead(&SP, 1, buf);
								else
										usleep(1000);
						} /* while */

						/* read the remaining 32 bytes of the packet */
						while (n<BUFLEN)
								if (serialInputPending(&SP))
										n += serialRead(&SP, (BUFLEN-n), buf+n);
								else
										usleep(100000);

						if (verbose>1) {
								for (i=0; i<BUFLEN; i++)
										printf("%02x ", buf[i]);
								printf("\n");
						}

						((FLOAT32_T *)(data->buf))[nchans*c + 0] = OPENBCI_CALIB1 * (buf[ 2]<<24 | buf[ 3]<<16 | buf[ 4]<<8)/255;
						((FLOAT32_T *)(data->buf))[nchans*c + 1] = OPENBCI_CALIB1 * (buf[ 5]<<24 | buf[ 6]<<16 | buf[ 7]<<8)/255;
						((FLOAT32_T *)(data->buf))[nchans*c + 2] = OPENBCI_CALIB1 * (buf[ 8]<<24 | buf[ 9]<<16 | buf[10]<<8)/255;
						((FLOAT32_T *)(data->buf))[nchans*c + 3] = OPENBCI_CALIB1 * (buf[11]<<24 | buf[12]<<16 | buf[13]<<8)/255;
						((FLOAT32_T *)(data->buf))[nchans*c + 4] = OPENBCI_CALIB1 * (buf[14]<<24 | buf[15]<<16 | buf[16]<<8)/255;
						((FLOAT32_T *)(data->buf))[nchans*c + 5] = OPENBCI_CALIB1 * (buf[17]<<24 | buf[18]<<16 | buf[19]<<8)/255;
						((FLOAT32_T *)(data->buf))[nchans*c + 6] = OPENBCI_CALIB1 * (buf[20]<<24 | buf[21]<<16 | buf[22]<<8)/255;
						((FLOAT32_T *)(data->buf))[nchans*c + 7] = OPENBCI_CALIB1 * (buf[23]<<24 | buf[24]<<16 | buf[25]<<8)/255;

						((FLOAT32_T *)(data->buf))[nchans*c + 8] = OPENBCI_CALIB2 * (buf[26]<<24 | buf[27]<<16)/32767;
						((FLOAT32_T *)(data->buf))[nchans*c + 9] = OPENBCI_CALIB2 * (buf[28]<<24 | buf[29]<<16)/32767;
						((FLOAT32_T *)(data->buf))[nchans*c +10] = OPENBCI_CALIB2 * (buf[28]<<24 | buf[31]<<16)/32767;

						c++;
				} /* while c<blocksize */

				sample += blocksize;
				printf("openbci2ft: sample count = %i\n", sample);

				/*
				 * Header
				 *   Byte 1: 0xA0
				 *   Byte 2: Sample Number
				 *
				 * EEG Data
				 * Note: values are 24-bit signed, MSB first
				 *   Bytes 3-5: Data value for EEG channel 1
				 *   Bytes 6-8: Data value for EEG channel 2
				 *   Bytes 9-11: Data value for EEG channel 3
				 *   Bytes 12-14: Data value for EEG channel 4
				 *   Bytes 15-17: Data value for EEG channel 5
				 *   Bytes 18-20: Data value for EEG channel 6
				 *   Bytes 21-23: Data value for EEG channel 6
				 *   Bytes 24-26: Data value for EEG channel 8
				 *
				 * Accelerometer Data
				 * Note: values are 16-bit signed, MSB first
				 *   Bytes 27-28: Data value for accelerometer channel X
				 *   Bytes 29-30: Data value for accelerometer channel Y
				 *   Bytes 31-32: Data value for accelerometer channel Z
				 *
				 * Footer
				 *   Byte 33: 0xC0
				 */

				/* create the request */
				request      = malloc(sizeof(message_t));
				request->def = malloc(sizeof(messagedef_t));
				request->buf = NULL;
				request->def->version = VERSION;
				request->def->bufsize = 0;
				request->def->command = PUT_DAT;
				request->def->bufsize = append(&request->buf, request->def->bufsize, data->def, sizeof(datadef_t));
				request->def->bufsize = append(&request->buf, request->def->bufsize, data->buf, data->def->bufsize);

				status = clientrequest(ftSocket, request, &response);
				if (verbose>0)
						fprintf(stderr, "openbci2ft: clientrequest returned %d\n", status);
				if (status) {
						fprintf(stderr, "openbci2ft: error in %s on line %d\n", __FILE__, __LINE__);
						exit(1);
				}

				if (status) {
						fprintf(stderr, "openbci2ft: error in %s on line %d\n", __FILE__, __LINE__);
						exit(1);
				}

				/* FIXME do someting with the response, i.e. check that it is OK */
				cleanup_message(&request);

				if (response == NULL || response->def == NULL || response->def->command!=PUT_OK) {
						fprintf(stderr, "Error when writing samples.\n");
				}
				cleanup_message(&response);

		} /* while keepRunning */

		/* stop streaming data */
		serialWrite(&SP, 1, "s");

		cleanup_data(&data);

		if (ftSocket > 0) {
				close_connection(ftSocket);
		} else {
				ft_stop_buffer_server(ftServer);
		}
		return 0;
} /* main */
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
  struct sockaddr_in si_me, si_other;
  socklen_t slen = sizeof(struct sockaddr_in);
  int udpsocket, n;
  char buf[BUFLEN];

  struct {
    uint16_t version;
    uint16_t nchans;
    uint16_t nbit;
    uint16_t fsample;
    uint16_t sec;
    uint16_t smp;
  } packet_v0;

  struct {
    uint8_t version;
    uint8_t nchans;
    uint16_t diagnostic_word;
    uint16_t mode_word;
    uint16_t fsample;
    uint32_t smp;
  } packet_v3;

  /* this is the common denominator of packet format v0 and v3 */
  struct {
    uint16_t version;
    uint16_t nchans;
    uint16_t nbit;
    uint16_t fsample;
    uint32_t smp;
  } packet;

  int sample = 0, status = 0, verbose = 0;
  host_t host;

  /* these represent the acquisition system properties */
  int nchans         = 16;   /* will be updated later on */
  int fsample        = 1000; /* will be updated later on */
  int nbit           = 16;
  int blocksize      = 43;

  /* these are used in the communication with the FT buffer and represent statefull information */
  int ftSocket           = -1;
  ft_buffer_server_t *ftServer;
  message_t    *request  = NULL;
  message_t    *response = NULL;
  header_t     *header   = NULL;
  data_t       *data     = NULL;

  printf(usage);

  if (argc>1)
    strcpy(host.name, argv[1]);
  else {
    strcpy(host.name, FTHOST);
  }

  if (argc>2)
    host.port = atoi(argv[2]);
  else {
    host.port = FTPORT;
  }

  fprintf(stderr, "jaga2ft: hostname     =  %s\n", host.name);
  fprintf(stderr, "jaga2ft: port         =  %d\n", host.port);

  /* Spawn tcpserver or connect to remote buffer */
  if (strcmp(host.name, "-") == 0) {
    ftServer = ft_start_buffer_server(host.port, NULL, NULL, NULL);
    if (ftServer==NULL) {
      fprintf(stderr, "jaga2ft: could not start up a local buffer serving at port %i\n", host.port);
      return 1;
    }
    ftSocket = 0;
    printf("jaga2ft: streaming to local buffer on port %i\n", host.port);
  }
  else {
    ftSocket = open_connection(host.name, host.port);

    if (ftSocket < 0) {
      fprintf(stderr, "jaga2ft: could not connect to remote buffer at %s:%i\n", host.name, host.port);
      return 1;
    }
    printf("jaga2ft: streaming to remote buffer at %s:%i\n", host.name, host.port);
  }  

  /* open the UDP server */
  if ((udpsocket=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
    diep("socket udp");
  int enable = 1;
  if (setsockopt(udpsocket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    diep("setsockopt");
  memset((char *) &si_me, 0, sizeof(si_me));
  si_me.sin_family      = AF_INET;
  si_me.sin_port        = htons(JAGAPORT);
  si_me.sin_addr.s_addr = htonl(INADDR_ANY);
  if (bind(udpsocket, &si_me, sizeof(si_me))==-1)
    diep("bind udp");

  /* allocate the elements that will be used in the communication to the FT buffer */
  request      = malloc(sizeof(message_t));
  request->def = malloc(sizeof(messagedef_t));
  request->buf = NULL;
  request->def->version = VERSION;
  request->def->bufsize = 0;

  header      = malloc(sizeof(header_t));
  header->def = malloc(sizeof(headerdef_t));
  header->buf = NULL;

  data      = malloc(sizeof(data_t));
  data->def = malloc(sizeof(datadef_t));
  data->buf = NULL;

  /* read the first packet to get some information */
  if ((n=recvfrom(udpsocket, buf, BUFLEN, 0, &si_other, &slen))==-1)
    diep("recvfrom()");
  if (verbose>0)
    printf("jaga2ft: received %d byte packet from %s:%d\n", n, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));

  /* parse the UDP package */
  if (buf[0]==0) {
    packet_v0.version = *(uint16_t *)(buf+0);
    packet_v0.nchans  = *(uint16_t *)(buf+2);
    packet_v0.nbit    = *(uint16_t *)(buf+4);
    packet_v0.fsample = *(uint16_t *)(buf+6);
    packet_v0.sec     = *(uint16_t *)(buf+8);
    packet_v0.smp     = *(uint16_t *)(buf+10);
    /* the packets are quite similar, the data starts at the same location */
    packet.version = packet_v0.version;
    packet.nchans  = packet_v0.nchans;
    packet.nbit    = packet_v0.nbit;
    packet.fsample = packet_v0.fsample;
    packet.smp     = packet_v0.smp;
  }
  else if (buf[0]==3) {
    packet_v3.version         = *(uint8_t  *)(buf+0);
    packet_v3.nchans          = *(uint8_t  *)(buf+1);
    packet_v3.diagnostic_word = *(uint16_t *)(buf+2);
    packet_v3.mode_word       = *(uint16_t *)(buf+4);
    packet_v3.fsample         = *(uint16_t *)(buf+6);
    packet_v3.smp             = *(uint32_t *)(buf+8);
    /* the packets are quite similar, the data starts at the same location */
    packet.version = packet_v3.version;
    packet.nchans  = packet_v3.nchans;
    packet.nbit    = 16;
    packet.fsample = packet_v3.fsample;
    packet.smp     = packet_v3.smp;
  }
  else {
    fprintf(stderr, "invalid packet version");
    exit(1);
  }

  /* update the defaults */
  nchans  = packet.nchans;
  fsample = packet.fsample;

  /* define the header */
  header->def->nchans    = nchans;
  header->def->nsamples  = 0;
  header->def->nevents   = 0;
  header->def->fsample   = fsample;
  header->def->data_type = DATATYPE_UINT16;
  header->def->bufsize   = 0;

  /* define the constant part of the data and allocate space for the variable part */
  data->def->nchans    = nchans;
  data->def->nsamples  = blocksize;
  data->def->data_type = DATATYPE_UINT16;
  data->def->bufsize   = WORDSIZE_UINT16*nchans*blocksize;

  /* initialization phase, send the header */
  request->def->command = PUT_HDR;
  request->def->bufsize = append(&request->buf, request->def->bufsize, header->def, sizeof(headerdef_t));
  request->def->bufsize = append(&request->buf, request->def->bufsize, header->buf, header->def->bufsize);

  /* this is not needed any more */
  cleanup_header(&header);

  status = clientrequest(ftSocket, request, &response);
  if (verbose>0) fprintf(stderr, "jaga2ft: clientrequest returned %d\n", status);
  if (status) {
    fprintf(stderr, "jaga2ft: could not send request to buffer\n");
    exit(1);
  }

  if (status || response==NULL || response->def == NULL) {
    fprintf(stderr, "jaga2ft: err2\n");
    exit(1);
  }

  cleanup_message(&request);

  if (response->def->command != PUT_OK) {
    fprintf(stderr, "jaga2ft: error in 'put header' request.\n");
    exit(1);
  }

  cleanup_message(&response);

  /* register CTRL-C handler */
  signal(SIGINT, abortHandler);

  printf("Starting to listen - press CTRL-C to quit\n");

  /* add a small pause between writing header + first data block */
  usleep(200000);

  while (keepRunning) 
  {

    if (verbose>1) 
      for (n=0; n<12; n++) 
	printf("buf[%2u] = %hhu\n", n, buf[n]);

    /* parse the UDP package */
    if (buf[0]==0) {
      packet_v0.version = *(uint16_t *)(buf+0);
      packet_v0.nchans  = *(uint16_t *)(buf+2);
      packet_v0.nbit    = *(uint16_t *)(buf+4);
      packet_v0.fsample = *(uint16_t *)(buf+6);
      packet_v0.sec     = *(uint16_t *)(buf+8);
      packet_v0.smp     = *(uint16_t *)(buf+10);
      /* the packets are quite similar, the data starts at the same location */
      packet.version = packet_v0.version;
      packet.nchans  = packet_v0.nchans;
      packet.nbit    = packet_v0.nbit;
      packet.fsample = packet_v0.fsample;
      packet.smp     = packet_v0.smp;
    }
    else if (buf[0]==3) {
      packet_v3.version         = *(uint8_t  *)(buf+0);
      packet_v3.nchans          = *(uint8_t  *)(buf+1);
      packet_v3.diagnostic_word = *(uint16_t *)(buf+2);
      packet_v3.mode_word       = *(uint16_t *)(buf+4);
      packet_v3.fsample         = *(uint16_t *)(buf+6);
      packet_v3.smp             = *(uint32_t *)(buf+8);
      /* the packets are quite similar, the data starts at the same location */
      packet.version = packet_v3.version;
      packet.nchans  = packet_v3.nchans;
      packet.nbit    = 16;
      packet.fsample = packet_v3.fsample;
      packet.smp     = packet_v3.smp;
    }
    else {
      fprintf(stderr, "invalid packet version");
      exit(1);
    }

    /* point to the data */
    data->buf = (buf+12);

    /* do some sanity checks */
    if (packet.nchans!=nchans) {
      fprintf(stderr, "jaga2ft: inconsistent number of channels %hu\n", packet.nchans);
      exit(1);
    }
    if (packet.nbit!=nbit) {
      fprintf(stderr, "jaga2ft: inconsistent number of bits %hu\n", packet.nbit);
      exit(1);
    }
    if (packet.fsample!=fsample) {
      fprintf(stderr, "jaga2ft: inconsistent sampling rate %hu\n", packet.fsample);
      exit(1);
    }

    /* create the request */
    request      = malloc(sizeof(message_t));
    request->def = malloc(sizeof(messagedef_t));
    request->buf = NULL;
    request->def->version = VERSION;
    request->def->bufsize = 0;
    request->def->command = PUT_DAT;
    request->def->bufsize = append(&request->buf, request->def->bufsize, data->def, sizeof(datadef_t));
    request->def->bufsize = append(&request->buf, request->def->bufsize, data->buf, data->def->bufsize);

    status = clientrequest(ftSocket, request, &response);
    if (verbose>0) fprintf(stderr, "jaga2ft: clientrequest returned %d\n", status);
    if (status) {
      fprintf(stderr, "jaga2ft: err3\n");
      exit(1);
    }

    if (status) {
      fprintf(stderr, "jaga2ft: err4\n");
      exit(1);
    }

    sample += blocksize;
    printf("jaga2ft: sample count = %i\n", sample);

    /* FIXME do someting with the response, i.e. check that it is OK */
    cleanup_message(&request);

    if (response == NULL || response->def == NULL || response->def->command!=PUT_OK) {
      fprintf(stderr, "Error when writing samples.\n");
    }
    cleanup_message(&response);

    /* read the next packet */
    if ((n=recvfrom(udpsocket, buf, BUFLEN, 0, &si_other, &slen))==-1)
      diep("recvfrom()");
    if (verbose>0)
      printf("jaga2ft: received %d byte packet from %s:%d\n", n, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));

  } /* while(1) */

  data->buf = NULL; /* this is not allocated on the heap but pointing to somewhere on the stack */
  cleanup_data(&data);
  close(udpsocket);

  if (ftSocket > 0) {
    close_connection(ftSocket);
  } else {
    ft_stop_buffer_server(ftServer);
  }
  return 0;
}
Exemplo n.º 7
0
int main(int argc, char *argv[]) {
  host_t host;
  
    /* these variables are for the threading */
  int rc;
  pthread_t tid;
  
    /* these variables are for writing the data */
  int i, j, k, status = 0, verbose = 0, samplecount = 0;
  time_t tic, toc;
  time_t elapsed;
  
  /* these represent the acquisition system properties */
  int fsample        = 512; /* this is just for the header */
  int nchans         = 32;
  int nsamples       = 64;
  int stateless      = 0;	  /* boolean */
  
  /* these are used in the communication and represent statefull information */
  int server             = -1;
  message_t    *request  = NULL;
  message_t    *response = NULL;
  header_t     *header   = NULL;
  data_t       *data     = NULL;
  event_t      *event    = NULL;
    
  
    /* start with defaults */
  sprintf(host.name, DEFAULT_HOSTNAME);
  host.port = DEFAULT_PORT;
  
  if (argc>1)
    sprintf(host.name, argv[1]);
  
  if (argc>2)
    host.port = atoi(argv[2]);
  
  if (argc>3)
    nchans = atoi(argv[3]);
  
  if (argc>4)
    nsamples = atoi(argv[4]);
  
  if (argc>5)
    stateless = atoi(argv[5]);
  

  check_datatypes();
  
  if (verbose>0) fprintf(stderr, "test_benchmark: host.name =  %s\n", host.name);
  if (verbose>0) fprintf(stderr, "test_benchmark: host.port =  %d\n", host.port);

  /* allocate the elements that will be used in the communication */
  request      = malloc(sizeof(message_t));
  request->def = malloc(sizeof(messagedef_t));
  request->buf = NULL;
  request->def->version = VERSION;
  request->def->bufsize = 0;
  
  header      = malloc(sizeof(header_t));
  header->def = malloc(sizeof(headerdef_t));
  header->buf = NULL;
  
  data      = malloc(sizeof(data_t));
  data->def = malloc(sizeof(datadef_t));
  data->buf = NULL;
  
  event      = malloc(sizeof(event_t));
  event->def = malloc(sizeof(eventdef_t));
  event->buf = NULL;
  
  /* define the header */
  header->def->nchans    = nchans;
  header->def->nsamples  = 0;
  header->def->nevents   = 0;
  header->def->fsample   = fsample;
  header->def->data_type = DATATYPE_FLOAT32;
  header->def->bufsize   = 0;
  FREE(header->buf);
  
  /* define the constant part of the data and allocate space for the variable part */
  data->def->nchans    = nchans;
  data->def->nsamples  = nsamples;
  data->def->data_type = DATATYPE_FLOAT32;
  data->def->bufsize   = WORDSIZE_FLOAT32*nchans*nsamples;
  FREE(data->buf);
  data->buf            = malloc(WORDSIZE_FLOAT32*nchans*nsamples);
    
    /* create the random data */
    for (j=0; j<nsamples; j++)
      for (i=0; i<nchans;    i++)
        ((FLOAT32_T *)(data->buf))[j*nchans+i] = 2.0*((FLOAT32_T)rand())/RAND_MAX - 1.0;
  
  /* initialization phase, send the header */
  request->def->command = PUT_HDR;
  request->def->bufsize = append(&request->buf, request->def->bufsize, header->def, sizeof(headerdef_t));
  request->def->bufsize = append(&request->buf, request->def->bufsize, header->buf, header->def->bufsize);
  
  server = open_connection(host.name, host.port);
  status = clientrequest(server, request, &response);
  if (verbose>0) fprintf(stderr, "test_benchmark: clientrequest returned %d\n", status);
  if (status) {
    fprintf(stderr, "random: err1\n");
    goto cleanup;
  }
  
  if (stateless) {
    status = close_connection(server);
    if (status) {
      fprintf(stderr, "random: err2\n");
      goto cleanup;
    }
  }
  
  cleanup_message(&request);
  cleanup_message(&response);
  request = NULL;
  response = NULL;
  
  tic = time(NULL);
  
  while (1) {
    
    /* create the request */
    request      = malloc(sizeof(message_t));
    request->def = malloc(sizeof(messagedef_t));
    request->buf = NULL;
    request->def->version = VERSION;
    request->def->bufsize = 0;
    request->def->command = PUT_DAT;
    request->def->bufsize = append(&request->buf, request->def->bufsize, data->def, sizeof(datadef_t));
    request->def->bufsize = append(&request->buf, request->def->bufsize, data->buf, data->def->bufsize);
    
    if (stateless)
      server = open_connection(host.name, host.port);
    
    status = clientrequest(server, request, &response);
    if (verbose>0) fprintf(stderr, "random: clientrequest returned %d\n", status);
    if (status) {
      fprintf(stderr, "random: err3\n");
      goto cleanup;
    }

    if (stateless) {
      status = close_connection(server);
      if (status) {
        fprintf(stderr, "random: err4\n");
        goto cleanup;
      }
    }

    cleanup_message(&request);
    cleanup_message(&response);
    request = NULL;
    response = NULL;
    
    samplecount += nsamples*nchans;
    toc = time(NULL);
    elapsed = toc-tic;
    
   fprintf(stderr, "samplecount = %d, elapsed = %d, samples/sec = %f\n", samplecount, elapsed, ((float)(samplecount))/((float)elapsed));
    
  } /* while(1) */
  
  cleanup:
    cleanup_event(&event);
    cleanup_data(&data);
    cleanup_header(&header);
    cleanup_message(&request);
    cleanup_message(&response);
    
    pthread_exit(0);
    return 0;
}
Exemplo n.º 8
0
int main(int argc, char *argv[]) {
  struct emokit_device* d;  
  struct emokit_frame c;

  int i, j, k, sample = 0, si=0, status = 0, verbose = 0;
  host_t host;

  /* these represent the acquisition system properties */
  int nchans         = NCHANS;
  int fsample        = FSAMPLE;
  int blocksize      = BLOCKSIZE;
  int channamesize   = 0;
  char *labelsbuf    = NULL;

  /* these are used in the communication and represent statefull information */
  int server             = -1;
  message_t    *request  = NULL;
  message_t    *response = NULL;
  header_t     *header   = NULL;
  data_t       *data     = NULL;
  emokit_samp_t *databuf  = NULL; // for holding the sample info
  event_t      *event    = NULL;
  ft_chunkdef_t chunkdef; // for holding the channel names

  if (argc>2) {
	 sprintf(host.name, "%s", argv[1]);
	 host.port = atoi(argv[2]);
  }
  else {
	 sprintf(host.name, "%s", DEFAULT_HOSTNAME);
	 host.port = DEFAULT_PORT;
  }

  if (verbose>0) fprintf(stderr, "emokit2ft: host.name =  %s\n", host.name);
  if (verbose>0) fprintf(stderr, "emokit2ft: host.port =  %d\n", host.port);

  //-------------------------------------------------------------------------------
  // open the emotive device
  d = emokit_create();
  k = emokit_get_count(d, EMOKIT_VID, EMOKIT_PID);
  printf("Current epoc devices connected: %d\n", k);
  for ( i=k; i<k; i--){
	 status = emokit_open(d, EMOKIT_VID, EMOKIT_PID, i);
	 if(status != 0)
		{
		  printf("CANNOT CONNECT: %d:%d\n", i,status);
		}
  }
  if ( status != 0 ) { 
	 printf("Could not connect to any device\nDo you have permission to read from : /dev/hidrawX\nsee https://github.com/openyou/emokit/issues/89"); 
	 return 1; 
  }
  printf("Connected\n");
  status = emokit_open(d, EMOKIT_VID, EMOKIT_PID, 1);
  if(status != 0)
	 {
		printf("CANNOT CONNECT: %d\n", status);
		return 1;
	 }
  printf("Connected\n");

  //-------------------------------------------------------------------------------
  /* allocate the elements that will be used in the buffer communication */
  request      = malloc(sizeof(message_t));
  request->def = malloc(sizeof(messagedef_t));
  request->buf = NULL;
  request->def->version = VERSION;
  request->def->bufsize = 0;

  header      = malloc(sizeof(header_t));
  header->def = malloc(sizeof(headerdef_t));
  header->buf = NULL; /* header buf contains the channel names */
  //header->buf = labels;

  data      = malloc(sizeof(data_t));
  data->def = malloc(sizeof(datadef_t));
  data->buf = NULL;

  event      = malloc(sizeof(event_t));
  event->def = malloc(sizeof(eventdef_t));
  event->buf = NULL;

  /* define the header */
  header->def->nchans    = nchans;
  header->def->nsamples  = 0;
  header->def->nevents   = 0;
  header->def->fsample   = fsample;
  header->def->data_type = DATATYPE_EMOKIT;
  header->def->bufsize   = 0;
  FREE(header->buf);
		
  //-------------------------------------------------------------------------------
  /* define the stuff for the channel names */
  /* compute the size of the channel names set */
  channamesize=0;
  for( i=0; i<nchans; i++){
	 for ( j=0; labels[i][j]!='\0'; j++); j++;
	 channamesize+=j;
  }
  /* allocate the memory for the channel names, and copy them into
	  it */
  labelsbuf = malloc(WORDSIZE_CHAR*channamesize);
  k=0;
  for( i=0; i<nchans; i++){
	 for ( j=0; labels[i][j]!='\0'; j++,k++) {
		labelsbuf[k]=labels[i][j];
	 }
	 labelsbuf[k]=labels[i][j]; k++;
  }
  chunkdef.type = FT_CHUNK_CHANNEL_NAMES;
  chunkdef.size = k;
  // add this info to the header buffer
  header->def->bufsize = append(&header->buf, header->def->bufsize, &chunkdef, sizeof(ft_chunkdef_t));
  header->def->bufsize = append(&header->buf, header->def->bufsize, labelsbuf, chunkdef.size);

  //-------------------------------------------------------------------------------
  /* initialization phase, send the header */
  request->def->command = PUT_HDR;
  request->def->bufsize = append(&request->buf, request->def->bufsize, header->def, sizeof(headerdef_t));
  request->def->bufsize = append(&request->buf, request->def->bufsize, header->buf, header->def->bufsize);

  server = open_connection(host.name, host.port);
  status = tcprequest(server, request, &response);
  if (verbose>0) fprintf(stderr, "emokit2ft: clientrequest returned %d\n", status);
  if (status) {
	 fprintf(stderr, "emokit2ft: put header error\n");
	 exit(1);
  }
  free(request->def);
  free(request);
		
  FREE(response->buf);
  if (response->def->command != PUT_OK) {
	 fprintf(stderr, "emokit2ft: error in 'put header' request.\n");
	 exit(1);
  }
  free(response->def);
  free(response);

  /* add a small pause between writing header + first data block */
  usleep(200000);


  //-------------------------------------------------------------------------------
  /* define the constant part of the data and allocate space for the variable part */
  data->def->nchans    = nchans;
  data->def->nsamples  = blocksize;
  data->def->data_type = DATATYPE_EMOKIT;
  data->def->bufsize   = WORDSIZE_EMOKIT * nchans * blocksize;
  FREE(data->buf);
  databuf              = malloc(WORDSIZE_EMOKIT*nchans*blocksize);
  data->buf            = databuf;

  //-------------------------------------------------------------------------------
  // Loop sending the data in blocks as it becomes available
  while (1) {

	 //-------------------------------------------------------------------------------
	 for ( si=0; si<blocksize; si++){ // get a block's worth of samples
		sample++;
		// wait until new data to get, 4 milliSec N.B. inter-sample ~= 8 milliSec
		while( emokit_read_data(d)<=0 ) { usleep(4000); } 
		/* get the new data */
		c = emokit_get_next_frame(d);
		if ( verbose>0 ) {
		  printf("%5d) %5d\t%5d\t%5d\t%5d\t%5d\t%5d\n", sample, c.counter, c.gyroX, c.gyroY, c.F3, c.FC6, c.P7);  
		  fflush(stdout);
		}
		// copy the samples into the data buffer, in the order we
		// *said* they should be
		databuf[(si*nchans)+0] =c.counter;
		databuf[(si*nchans)+1] =c.AF3 - eeg_zero_offset;
		databuf[(si*nchans)+2] =c.F7  - eeg_zero_offset;
		databuf[(si*nchans)+3] =c.F3  - eeg_zero_offset;
		databuf[(si*nchans)+4] =c.FC5 - eeg_zero_offset;
		databuf[(si*nchans)+5] =c.T7  - eeg_zero_offset;
		databuf[(si*nchans)+6] =c.P7  - eeg_zero_offset;
		databuf[(si*nchans)+7] =c.O1  - eeg_zero_offset;
		databuf[(si*nchans)+8] =c.O2  - eeg_zero_offset;
		databuf[(si*nchans)+9] =c.P8  - eeg_zero_offset;
		databuf[(si*nchans)+10]=c.T8  - eeg_zero_offset; 
		databuf[(si*nchans)+11]=c.FC6 - eeg_zero_offset;
		databuf[(si*nchans)+12]=c.F4  - eeg_zero_offset;
		databuf[(si*nchans)+13]=c.F8  - eeg_zero_offset;
		databuf[(si*nchans)+14]=c.AF4 - eeg_zero_offset;
		databuf[(si*nchans)+15]=c.gyroX;
		databuf[(si*nchans)+16]=c.gyroY;
	 }


	 //-------------------------------------------------------------------------------
	 /* create the request */
	 /* TODO: re-use the request structures rather than re-allocating
		 every time */
	 request      = malloc(sizeof(message_t));
	 request->def = malloc(sizeof(messagedef_t));
	 request->buf = NULL;
	 request->def->version = VERSION;
	 request->def->command = PUT_DAT;
	 request->def->bufsize = 0;
	 request->def->bufsize = append(&request->buf, request->def->bufsize, data->def, sizeof(datadef_t));
	 request->def->bufsize = append(&request->buf, request->def->bufsize, data->buf, data->def->bufsize);
				
	 status = tcprequest(server, request, &response);
	 if (verbose>0) fprintf(stderr, "emokit2ft: clientrequest returned %d\n", status);
	 if (status) {
		fprintf(stderr, "emokit2ft: err3\n");
		exit(1);
	 }				
	 cleanup_message((void**)&request);
				
	 if (response == NULL || response->def == NULL || response->def->command!=PUT_OK) {
		fprintf(stderr, "Error when writing samples.\n");
	 }
	 cleanup_message((void**)&response);
  } /* while(1) */

  // free all the stuff we've allocated
  free(labelsbuf);
  free(databuf);
  cleanup_message((void**)&header);
  cleanup_message((void**)&event);
  cleanup_message((void**)&data);
}