#include "common.h"

#include <math.h>

// https://en.wikipedia.org/wiki/Steinhart%E2%80%93Hart_equation
// https://onlinelibrary.wiley.com/doi/abs/10.1002/andp.18280890511
// https://onlinelibrary.wiley.com/doi/abs/10.1002/andp.18441370202
// https://bmcnoldy.earth.miami.edu/Humidity.html

// TODO: Is resistance function semantically correct?
// TODO: Check results for humidity conversion functions.

// Thermistor general constants
#define R1    10000.0f  // Resistor ohm value
#define VRES  0xFFFF    // 16-bit ADC resolution

// Thermistor coeficients
#define SC1  1.009249522e-3f
#define SC2  2.378405444e-4f
#define SC3  2.019202697e-7f

// Humidity conversion constants
#define TH1  100.0f
#define TH2  243.04f
#define TH3  17.625f

float Resistance(int adc_raw)
{
	float r2;

	// TODO: Improve readability.
	// TODO: Make sure output is correct.

	// [GND] - [10K RESISTOR] - [ADC INPUT] - [THERMISTOR] - [VCC]

	// return ((VRES - adc_raw) * R1) / adc_raw;
	r2 = (float) adc_raw / 264.8f * 0.05f;

	return R1 / (5.0f / r2 - 1.0f);
}

float SteinhartHart(float res)
{
	float logr, t;

	// Convert resistance to temperature

	//  25C = 10000 Ohms
	// 100C =  6744 Ohms

	logr = log(res);
	t = 1.0f / (SC1 + SC2 * logr + SC3 * pow(logr, 3));

	return t - 273.15f; // Kelvin to celsius
}

float Dewpoint(float t, float rh)
{
	float a, b;

	// 243.04*(LN(RH/100)+((17.625*T)/(243.04+T)))/
	// (17.625-LN(RH/100)-((17.625*T)/(243.04+T)))

	a = log(rh / TH1);
	b = TH3 * t / (TH2 + t);

	return TH2 * (a + b) / (TH3 - a - b);
}

float Temperature(float td, float rh)
{
	float a, b;

	// 243.04*(((17.625*TD)/(243.04+TD))-LN(RH/100))/
	// (17.625+LN(RH/100)-((17.625*TD)/(243.04+TD)))

	a = log(rh / TH1);
	b = TH3 * td / (TH2 + td);

	return TH2 * (b - a) / (TH3 + a - b);
}

float RelHumidity(float t, float td)
{
	float a, b;

	// 100*(EXP((17.625*TD)/(243.04+TD))/
	//      EXP((17.625*T)/(243.04+T)))

	a = TH3 * td / (TH2 + td);
	b = TH3 * t / (TH2 + t);

	return TH1 * (exp(a) / exp(b));
}
