#!/usr/bin/env python3

import os
import sys
import numpy as np

license_header = """/* Reflow Oven Controller
*
* Copyright (C) 2020  Mario Hüttel <mario.huettel@gmx.net>
*
* This file is part of the Reflow Oven Controller Project.
*
* The reflow oven controller is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* The Reflow Oven Control Firmware is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the reflow oven controller project.
* If not, see <http://www.gnu.org/licenses/>.
*/

"""

hfile="temp-converter-data.h"

project_dir = os.path.dirname(os.path.realpath(__file__))
include_prefix = 'reflow-controller'
module_include_dir = os.path.join(project_dir, os.path.join('include', include_prefix))
include_file = os.path.join(module_include_dir, hfile)

h_define = '__'+hfile.replace('.', '_').replace('-', '_').upper()+'__'

min_res = 1000
max_res = 2200
res_step = 20

R_zero = 1000.0
A = 3.9083E-3
B = -5.7750E-7

def calc_temp(resistance):
    temp = (-R_zero * A + np.sqrt(R_zero*R_zero * A * A - 4* R_zero * B * (R_zero - resistance)))/(2*R_zero*B)
    return temp

if ((max_res-min_res) % res_step) != 0:
	print('Resistance range must be a multiple of res_step!')
	sys.exit(-1)

print('Calculating temperature table for %f Ohm to %f Ohm in %f Ohm steps' % (min_res, max_res, res_step))

temp_array = ''

for res in range(min_res, max_res+res_step, res_step):
	temp = calc_temp(res)
	temp_array = temp_array+ ',%.2ff' % temp

temp_array = temp_array[1:]

with open(include_file, 'x') as f:
	f.write(license_header)
	f.write('\n')
	f.write('#ifndef %s\n' % h_define)
	f.write('#define %s\n\n' % h_define)
	f.write('#define TEMP_CONVERSION_ARRAY_DATA %s\n' % temp_array)
	f.write('#define TEMP_CONVERSION_MIN_RES %d\n' % min_res)
	f.write('#define TEMP_CONVERSION_MAX_RES %d\n' % max_res)
	f.write('#define TEMP_CONVERSION_RES_STEP %d\n' % res_step)
	f.write('\n')
	f.write('#endif /* %s */\n' % h_define)
