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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

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 check(int error) {
	if (error!=0) {
		fprintf(stderr, "Error: %s\n", strerror(error));
		exit(EXIT_FAILURE);
	}
}

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

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

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;
}
