

import math

# ---- Conversion functions

VREF = 2.5 # Volts

R1 = 10000 # Ohm
R2 = 2200 # Ohm
R3 = 27000 # Ohm
R4 = 30000 # Ohm
R5 = 27000 # Ohm
R6 = 56000 # Ohm

RREF = 28.7 # Ohm (current-setting resistor) @1550 nm - 28.7 Ohm; @840 nm - 10 Ohm

R7 = 22000 # Ohm
R8 = 22000 # Ohm
R9 = 5100 # Ohm
R10 = 180000 # Ohm

class Task:
    def __init__(self):
        self.task_type = 0
        # Here should be fields, contained task parameters

def conv_T_C_to_N(T):
    Rt = 10000 * math.exp( 3900/(T+273) - 3900/298 )
    U = VREF/(R5*(R3+R4)) * ( R1*R4*(R5+R6) - Rt*(R3*R6-R4*R5) ) / (Rt+R1)
    N = int(U * 65535 / VREF)
    if N<0 or N>65535:
        print("Error converting T=" + str(T) + " to N=" + str(N) + ". N should be within [0, 65535]. Returning N=0.")
    return N

def conv_T_N_to_C(N):
    U = N*VREF/65535 # Volts
    Rt = R1 * (VREF*R4*(R5+R6) - U*R5*(R3+R4)) / (U*R5*(R3+R4) + VREF*R3*R6 - VREF*R4*R5) # Ohm
    T = 1 / (1/298 + 1/3900 * math.log(Rt/10000)) - 273 # In Celsius
    return T

def conv_TExt_N_to_C(N):
    U = N*VREF/4095*1/(1+100000/R10) + VREF*R9/(R8+R9) # Volts
    Rt = R7*U/(VREF-U) # Ohm
    T = 1 / (1/298 + 1/3455 * math.log(Rt/10000)) - 273 # In Celsius
    return T

def conv_I_mA_to_N(I):
    N = int(65535/2000 * RREF * I) # I in mA
    if N<0 or N>65535:
        print("Error converting I=" + str(I) + " to N=" + str(N) + ". N should be within [0, 65535]. Returning N=0.")
        N=0
    return N

def conv_I_N_to_mA(N):
    return N*2.5/(65535*4.4) - 1/20.4 # I in mA


def conv_U3V3_N_to_V(u_int):
    return u_int * 1.221 * 0.001 # Volts

def conv_U5V_N_to_V(u_int):
    return u_int * 1.8315 * 0.001 # Volts

def conv_U7V_N_to_V(u_int):
    return u_int * 6.72 * 0.001 # Volts


