// Modificeret fra: https://www.xanthium.in/Serial-Port-Programming-on-Linux
// Programmet venter på en char på com porten, og printer den ud
// når den kommer

// Testet på RPi med hjælp af CLI komandoer ...
// echo "TEST" > /dev//ttyAMA0 (Sender data til port
// cat < /dev/ttyAMA0 (Læser fra port


#include <stdio.h>
#include <fcntl.h>  /* File Control Definitions          */
#include <termios.h>/* POSIX Terminal Control Definitions*/
#include <unistd.h> /* UNIX Standard Definitions         */
#include <errno.h>  /* ERROR Number Definitions          */

#define PORT "/dev/ttyAMA0"

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;		// Block = 1, nonblok = 0
    tty.c_cc[VTIME] = 10;	// Timeout 1 sek

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}


int main()
{
  int fd,i;
  unsigned char tmp[10];

  fd = open(PORT, O_RDWR | O_NOCTTY | O_SYNC);
  if(fd == 1)
     printf("\n  FEJL! %s\n", PORT);
  i = 0;
  set_interface_attribs(fd, B115200);
	do {
		i=read(fd,tmp,1);
		if (i>0)
			printf(" : %d", tmp[0]);
		if (i==-1)
			printf("FEJL! %d",i);
		if (i==0)
			printf("EOF\n");
		fflush(NULL);	// Emty buffer
	} while(1);
  close(fd);
  printf("\n");
  return 0;
}

