#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

double readTemp(void) {
//  dummy: should read temperature from ADC
    static double val = 0.0;
    val += 0.5;
    if (val > 20.0)
        val = 0.0;
    return val;
}

void writeSwitch(int i) {
//  dummy: should write to switch
}

double readPres(void) {
//  dummy: should read pressure from ADC
    static double val = 20.0;
    val -= 0.4;
    if (val < 0.0)
        val = 20.0;
    return val;
}

void writeDAC(double d) {
//  dummy: should write to DAC
}

int tempControl(double temp) {
//  dummy: should use better algorithm
    static struct timespec ms100 = {0, 100000000};
    nanosleep(&ms100, NULL);
    return temp > 10.0;
}

double presControl(double pres) {
//  dummy: should use better algorithm
    static struct timespec ms100 = {0, 100000000};
    nanosleep(&ms100, NULL);
    return 10.0 - pres;
}

void* tempThread(void* p) {
    double temp;
    int switch_;
    while (1) {
        temp = readTemp();
        printf("temperature = %4.1lf", temp);
        switch_ = tempControl(temp);
        printf(", switch = %d\n", switch_);
        writeSwitch(switch_);
        sleep(3);
    }
    return NULL;
}

void* presThread(void* p) {
    double pres, dac;
    while (1) {
        pres = readPres();
        printf("pressure = %4.1lf", pres);
        dac = presControl(pres);
        printf(", DAC = %5.1lf\n", dac);
        writeDAC(dac);
        sleep(1);
    }
    return NULL;
}

void check(int error) {
    if (error != 0) {
        fprintf(stderr, "Error: %s\n", strerror(error));
        exit(EXIT_FAILURE);
    }
}

int main(void) {
    pthread_t t1, t2;

    check( pthread_create(&t1, NULL, tempThread, NULL) );
    check( pthread_create(&t2, NULL, presThread, NULL) );

    check( pthread_join(t1, NULL) );
    check( pthread_join(t2, NULL) );

    return EXIT_SUCCESS;
}
