/* 
 * File:   main.cpp
 * Author: Jan Hudec
 *
 * Created on 16. května 2019, 16:54
 */

// generic libraries
#include <cstdlib>
#include <iostream>
#include <stdio.h>

// for unbuffered input read
#include <sys/ioctl.h>
#include <termios.h>
#include <stdbool.h>
#include <unistd.h>

// custom libraries
#include "mega_meg44pan_simulator.h"

// iec dependent libraries
#include <sv_publisher.h>
#include <goose_publisher.h>


int kbhit(void);

int main(int argc, char** argv)
{
    printf("\nMEgA MEg44PAN Simulator, using libiec61850 library\n");

    mega_meg44pan_simulator sim;

    try
    {
        sim.parse_config("meg44pan_config.cfg");
        
        printf("Running. Press CTRL+C to quit.\nPress S to create a spike in values.\n");

        uint64_t time_old = Hal_getTimeInMs();
        bool running = true;
        char input;
        
        while (running)
        {
            if (Hal_getTimeInMs() - time_old >= sim.time_treshold)
            {
                sim.generate_voltages();
                sim.save_voltages("voltage_values.txt");
                time_old = Hal_getTimeInMs();
            }
            
            if(kbhit())
            {
                input = getchar();
                if(input == 's')
                {
                    sim.spike = true;
                }
                else
                {
                    fflush(stdout);
                }
            }
        }
    }
    catch (const std::exception& e)
    {
        printf("Caught exception: %s\n", e.what());
    }

    return 0;
}

int kbhit(void)
{
    static bool initflag = false;
    static const int STDIN = 0;

    if (!initflag)
    {
        // use termios to turn off line buffering
        struct termios term;
        tcgetattr(STDIN, &term);
        term.c_lflag &= ~ICANON;
        term.c_lflag &= ~ECHO;
        tcsetattr(STDIN, TCSANOW, &term);
        setbuf(stdin, NULL);
        initflag = true;
    }

    int nbbytes;
    ioctl(STDIN, FIONREAD, &nbbytes);  // 0 is STDIN
    return nbbytes;
}