// gcc -Wall -lm -O2 -pipe -std=c99 bitbang_terminal.c -o bitbang_terminal
#define _BSD_SOURCE 1

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[]) {
  struct termios term_opt;

  int fd = open("/dev/ttyUSB0", O_RDWR);

  if(fd < 0) {
    perror("argh");
    return -1;
  }

  tcgetattr(fd, &term_opt);

  cfmakeraw(&term_opt);
  cfsetispeed(&term_opt, B1200);
  cfsetospeed(&term_opt, B1200);
  tcsetattr(fd, TCSAFLUSH, &term_opt);

  while (1) {
    char line[256];
    if (NULL == fgets(line, sizeof(line), stdin)) {
      perror("input");
      return -3;
    }
    if (write(fd, line, strlen(line)) < 0) {
      perror("send error");
      return -4;
    }

    for (int i = 0; i < sizeof(line); i++) {
      line[i] = 0;
    }
    sleep(1);
    int read_bytes = read(fd, line, sizeof(line));
    if (read_bytes <= 0) {
      perror("read error");
      return -5;
    }
    line[read_bytes] = '\0';
    printf("received (%d): %s", read_bytes, line);
    printf(" (");
    for (int i = 0; i < read_bytes; i++) {
      if (i > 0) {
        printf(" ");
      }
      printf("0x%X", line[i]);
    }
    printf(")\n");
  }
}
