/*
 * Filename: mpa-alrm.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#include <termios.h> 
#include <unistd.h>  // for STDIN_FILENO

#include <pthread.h>

#include "prg_io_nonblock.h"

#define PERIOD_STEP 10
#define PERIOD_MAX 2000
#define PERIOD_MIN 10

#define READ_TIMOUT_MS 500 //timeout for reading from pipe, quite high but due to 5 seconds alarm it is ok

enum {
   ERROR_FILE_IO = 100
};

typedef struct {
   // share data among threads, access using critical section (mtx (un)lock)
   // mininal example to show blocked io_open_write() from mpa-ctrl 
   int fd_in; // file descriptor 
} data_t;


// possible thread functions 
void* in_pipe_thread(void*);
void* out_pipe_thread(void*);
void* alarm_thread(void*);

// - main ---------------------------------------------------------------------
int main(int argc, char *argv[])
{ 
   // replace the minimal example to open the pipe for reading
  
   data_t data = { .fd_in = -1 };

   const char *in = argc > 1 ? argv[1] : "/tmp/mpa-alrm.in";

   fprintf(stderr, "DEBUG(%s) io_open_read(%s) ... ", __func__, in);
   data.fd_in = io_open_read(in);
   fprintf(stderr, "done\n");

   int *ex = in_pipe_thread(&data);

   fprintf(stderr, "DEBUG(%s) in_pipe_thread return value: %d\n", __func__, *ex);
   io_close(data.fd_in);

   return EXIT_SUCCESS;
}

// - function -----------------------------------------------------------------
void* in_pipe_thread(void *d)
{
   data_t *data = (data_t*)d;
   static int r = 0;
   // place your code here and replace the minimal example keeping the pipe alive
   bool q = false; // it should q = data->quit within critical section

   while (!q) {
      unsigned char c;
      int rio = io_getc_timeout(data->fd_in, READ_TIMOUT_MS, &c);
      fprintf(stderr, "DEBUG(%s) io_getc_timeout() r: %i c: %i\n", __func__, rio, c);
      if (rio == 0) { // just timeout
	 continue;
      }
      if (rio == 1 && c == 'b') { // 'b' received 
	 q = true;
      } else { // error reading or 
	 r = ERROR_FILE_IO;
      }
   } //end while loop
   return &r;
}

// - function -----------------------------------------------------------------
void* out_pipe_thread(void *d)
{
   // data_t *data = (data_t*)d;
   static int r = 0;
   // place your code here
   return &r;
}

// - function -----------------------------------------------------------------
void* alarm_thread(void *d)
{
   // data_t *data = (data_t*)d;
   static int r = 0;
   return &r;
}

/* end of mpa-alrm.c */
