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

#define SERIAL_PORT "/dev/tty.usbmodemfa1311"
#define BAUDRATE B9600
#define BUFSIZE 256

#define TRUE 1;
#define FALSE 0;

int main(int argc, char* argv[])
{
    printf("program start\n");
    int fd = open(SERIAL_PORT, O_RDWR);
    printf("open");
    if (fd == -1) {
        
        perror("Unable to open serial port\n");
        return -1;
    }
    
    printf("opened\n");
    // 既存のシリアルの設定を取得
    struct termios old_options;
    int ret;
    ret = tcgetattr(fd, &old_options);
    
    /*
    
    // 新しいシリアルの設定を適用
    memset(&new_options, 0, sizeof(new_options));
    new_options.c_cflag = CS8 | CLOCAL | CREAD;
    new_options.c_cc[VTIME] = 0;
    new_options.c_lflag = ICANON;
    new_options.c_iflag = IGNPAR | ICRNL;
    cfsetispeed(&new_options, BAUDRATE);
    cfsetospeed(&new_options, BAUDRATE);
    tcsetattr(fd, TCSANOW, &new_options);
    
    // 通信処理
    int count;
    volatile int STOP = 0;
    char readbuf[BUFSIZE];
    printf("start\n");
    while(STOP == 0){
        memset(readbuf, 0, sizeof(readbuf));
        count = (int)read(fd, &readbuf, BUFSIZE);
        if(count < 0){
            fprintf(stdout, "end\n");
            STOP = 1;
        }else{
            fprintf(stdout, "recv:%s(%d)\n", readbuf, count);
        }
    }
     */
    
    // シリアルの設定を既存のものに戻して終了
    ret = tcsetattr(fd, TCSANOW, &old_options);
    close(fd);
    
    printf("end\n");
    return 0;
}
