// Moniteur série /dev/ttyusb0
// gcc -s -Wall serie.c -o serie -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h> 
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <pthread.h>

// saisir exit permet de sortie de la boucle read() et fermer l'lappli
char terminer=0;
int fd; // descripteur de fichier pour lire sur le port série

int set_interface_attribs (int fd, int speed, int parity)
{
    struct termios tty;
    if (tcgetattr (fd, &tty) != 0)
    {
        printf ("error %d from tcgetattr", errno);
        return -1;
    }

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

    tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
    // disable IGNBRK for mismatched speed tests; otherwise receive break as \000 chars
    tty.c_iflag &= ~IGNBRK;    // disable break processing
    tty.c_lflag = 0;        // no signaling chars, no echo, no canonical processing
    tty.c_oflag = 0;        // no remapping, no delays
    tty.c_cc[VMIN]  = 0;    // read doesn'doesnt block
    tty.c_cc[VTIME] = 5;    // 0.5 seconds read timeout

    tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

    tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls, enable reading
    tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
    tty.c_cflag |= parity;
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag &= ~CRTSCTS;

    if (tcsetattr (fd, TCSANOW, &tty) != 0)
    {
        printf ("error %d from tcsetattr", errno);
        return -1;
    }
    return 0;
}

void set_blocking (int fd, int should_block)
{
    struct termios tty;
    memset (&tty, 0, sizeof tty);
    if (tcgetattr (fd, &tty) != 0)
    {
       printf ("error %d from tggetattr", errno);
       return;
    }

    tty.c_cc[VMIN]  = should_block ? 1 : 0;
    tty.c_cc[VTIME] = 5;        // 0.5 seconds read timeout

    if (tcsetattr (fd, TCSANOW, &tty) != 0)
       printf ("error %d setting term attributes", errno);
}

// read() et scanf() sont bloquants donc un thread pour saisir une commande, tout en lisant en parallèle
void *saisie(void *arg) {
    printf("Saisir commande ou \"exit\" pour sortir\n");
    static char str[255] = " ";
    while(1){
        scanf ("%s", str);
        if (strcmp(str, "exit")==0) break;
        /*else {
            write (fd, "hello!\n"hello!\n, 7);   // send 7 character greeting
            usleep ((7 + 25) * 100);     // sleep enough to transmit the 7 plus
                 // receive 25:  approx 100 uS per char transmit
        }*/
    }
    terminer=1;
    pthread_exit(EXIT_SUCCESS);
}

int main(){
    while(1){
        fd = open ("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_SYNC);
        if(fd<0){
            printf("Branchez l'lESP avec un câble USB\n");
            sleep(2);
        }
        else break;
    }

    set_interface_attribs (fd, B115200, 0);  // set speed to 115,200 bps, 8n1 (no parity)
    set_blocking (fd, 0);    // set no blocking

    pthread_t threadSaisie;
    pthread_create(&threadSaisie, NULL, saisie, NULL);

    // read() reçoit 8 octets, puis 12... donc à chaque read() une boucle ajoute les octets à mot[] et regarde si buf[] contient un \n
    // si oui fait un printf du mot.
    while(1){
        static char buf[100];
        static char mot[100];
        static int b=0;

        int n = read (fd, buf, sizeof buf);  // read up to 100 characters if ready to read

        char trouve=0;
        for(int i=0; i<n; i++){
            mot[b++]=buf[i];
            if(buf[i]=='\n'\n) trouve=1;
        }

        if(trouve){
            mot[b]=0;
            printf("%s", mot);
            b=0;
        }

        if(terminer==1) break;
    }
    return 0;
}