// file: /stm32/burn/term.c	11/11/2020	Don Stoner
//
#include <ncurses.h>	// To get this code: sudo apt-get install libncurses5-dev
//#include <stdio.h>	// stdio.h is unnecessary because ncurses already contains it
//#include <wiringPi.h>	// this is also unnecessary (we only need its serial stuff):
#include <wiringSerial.h>

//---------------------------------------------------------------------------------------------
//
// Main Routine:
//
void main() {
	//	Setup for ncurses (captures  single keystrokes)
	//
	initscr();	// initiate the curses code
	scrollok(stdscr,TRUE);	// enable screen scrolling
	raw();		// get just one character at a time (option)
			// or: cbreak(); same as "raw" but allows ^c and etc. to work
	noecho();	//		supress automatic character echoing (option)
	keypad(stdscr, TRUE); //	also capture special keys: (option)
	// KEY_DOWN  KEY_UP  KEY_LEFT  KEY_RIGHT  KEY_F(n)  KEY_ENTER
	// KEY_HOME  KEY_BACKSPACE  KEY_DC (delete)  KEY_IC (insert)
	nodelay(stdscr, TRUE);// returns ERR (-1) if no key is ready (option)

	//	Setup for terminal loop
	//
	printw("Terminal Program:  /dev/serial0 115200 baud  (^X to exit)\n");
	int fd=serialOpen ("/dev/serial0", 115200);	// open serial port

	//	Loop reading one key per loop
	//	exit following control-X
	//
	int ch = -1; 	//	First loop != 3 (exit)
	for (; ch != 0x18 ; ch == KEY_ENTER) {	// 0x18 => ^x => exit
		ch = getch();		// get a key (or immediate -1)
		if(ch != -1) {  // OUTPUT
			serialPutchar (fd, ch);		// output serial keycode
		} else {	// INPUT
			if (serialDataAvail(fd) > 0) {	// # of characters available > 0?
				// read (and echo) serial inputs (only when present)
				ch=serialGetchar(fd);	// (else times out after 10 seconds)
				echochar(ch);		// disply received character
			}
		}
	}

	//	Shutdown
	//
	serialClose (fd);	// close serial connection
	endwin();	// restore normal terminal settings
}

//---------------------------------------------------------------------------------------------
// usage:
//	nano term.c
//	gcc -o term term.c -l ncurses -l wiringPi
//	./term

