#include <general.h>
#include <unistd.h>
#include <fcntl.h>
#include <rtt_if.h>
#ifndef WIN32
#include <termios.h>
typedef struct termios terminal_io_state_s;
static terminal_io_state_s saved_ttystate;
static bool tty_saved = false;
int rtt_if_init()
{
terminal_io_state_s ttystate;
tcgetattr(STDIN_FILENO, &saved_ttystate);
tty_saved = true;
tcgetattr(STDIN_FILENO, &ttystate);
ttystate.c_lflag &= ~ICANON;
ttystate.c_lflag &= ~ECHO;
ttystate.c_cc[VMIN] = 1;
tcsetattr(STDIN_FILENO, TCSANOW, &ttystate);
int flags = fcntl(0, F_GETFL, 0);
fcntl(0, F_SETFL, flags | O_NONBLOCK);
return 0;
}
int rtt_if_exit()
{
if (tty_saved)
tcsetattr(STDIN_FILENO, TCSANOW, &saved_ttystate);
return 0;
}
uint32_t rtt_write(const char *buf, uint32_t len)
{
int unused = write(1, buf, len);
(void)unused;
return len;
}
int32_t rtt_getchar()
{
char ch;
int len;
len = read(0, &ch, 1);
if (len == 1)
return ch;
return -1;
}
bool rtt_nodata()
{
return false;
}
#else
int rtt_if_init()
{
return 0;
}
int rtt_if_exit()
{
return 0;
}
uint32_t rtt_write(const char *buf, uint32_t len)
{
write(1, buf, len);
return len;
}
int32_t rtt_getchar()
{
return -1;
}
bool rtt_nodata()
{
return false;
}
#endif