/***************************************************************************/
/*                             Druckersoftware                             */
/*                    Copyright (C) Carl Valentin GmbH                     */
/***************************************************************************/

/*
 * test_data_line_xon_xoff.h
 *
 *  Created on: 02.05.2022
 *      Author: preitinger
 */

#ifndef TEST_TEST_DATA_LINE_XON_XOFF_H_
#define TEST_TEST_DATA_LINE_XON_XOFF_H_

#ifdef TEST_DATA_LINE_XON_XOFF

typedef struct {
    unsigned char startChar, stopChar;
    struct task_struct* t;
} TestDataLineXonXoffEnv;

static TestDataLineXonXoffEnv test_data_line_xon_xoff_env;

int test_data_line_xon_xoff_init(void) {
    TestDataLineXonXoffEnv* e = &test_data_line_xon_xoff_env;

    e->startChar = e->stopChar = 0;
    e->t = NULL;
    return 0;
}

void test_data_line_xon_xoff_exit(void) {
    // TODO

}

void test_data_line_xon_xoff_onOpen(void) {
    // TODO ?
}

int test_data_line_xon_xoff_threadfn(void* data) {
    TestDataLineXonXoffEnv* e = &test_data_line_xon_xoff_env;
    int res;

    msleep(1000);


    res = tty_insert_flip_char(&cv_port[0].port, 'X', TTY_NORMAL);
    ASSERT(1 == res);
    res = tty_insert_flip_char(&cv_port[0].port, 'Y', TTY_NORMAL);
    ASSERT(1 == res);
    tty_flip_buffer_push(&cv_port[0].port);

    res = tty_insert_flip_char(&cv_port[0].port, 0, TTY_BREAK);
    ASSERT(1 == res);
#if 0
    tty_ldisc_flush(cv_port[0].port.tty);
#endif


    res = tty_insert_flip_char(&cv_port[0].port, e->startChar, TTY_NORMAL);
    ASSERT(1 == res);
    res = tty_insert_flip_char(&cv_port[0].port, 'c', TTY_NORMAL);
    ASSERT(1 == res);
    res = tty_insert_flip_char(&cv_port[0].port, 'b', TTY_NORMAL);
    ASSERT(1 == res);
//    res = tty_insert_flip_char(&cv_port[0].port, '\r', TTY_NORMAL);
//    ASSERT(1 == res);
//    res = tty_insert_flip_char(&cv_port[0].port, '\n', TTY_NORMAL);
//    ASSERT(1 == res);
    res = tty_insert_flip_char(&cv_port[0].port, e->stopChar, TTY_NORMAL);
    ASSERT(1 == res);
    tty_flip_buffer_push(&cv_port[0].port);

    pr_info("Ende test_data_line_xon_xoff_threadfn\n");
    return 0;
}

void test_data_line_xon_xoff_termios(unsigned char startChar, unsigned char stopChar) {
    TestDataLineXonXoffEnv* e = &test_data_line_xon_xoff_env;

    e->startChar = startChar;
    e->stopChar = stopChar;

//    if (!e->t) {
        // kthread starten, der nach 100ms ein xon in den data line buffer schreibt

        e->t = kthread_create(test_data_line_xon_xoff_threadfn, NULL, "test_data_line_xon_xoff_threadfn");
        ASSERT(!IS_ERR(e->t));
        wake_up_process(e->t);
//    }
}

void test_data_line_xon_xoff_write(const unsigned char *buffer, int count) {
    int i;

    pr_info("\n\n");

    for (i = 0; i < count; ++i) {
        pr_info("write[%d]: 0x%x\n", i, (int) buffer[i]);
    }

    pr_info("\n\n");
}

#endif // ifdef TEST_DATA_LINE_XON_XOFF


#endif /* TEST_TEST_DATA_LINE_XON_XOFF_H_ */
