#include "Actuator.h"
#include "confOrdi.h"
#include "i2c.h"
#include "tim.h"

void Actuator_init() {
	Actuator_t[0].type = ECUMEUR;
	Actuator_t[0].address = ADDECUMEUR;
	Actuator_t[0].bobine = BOBECUMEUR;
	Actuator_t[0].active = 1;

	Actuator_t[1].type = BRASSAGE1;
	Actuator_t[1].address = ADDBRASSAGE1;
	Actuator_t[1].bobine = BOBBRASSAGE1;
	Actuator_t[1].active = 1;

	Actuator_t[2].type = BRASSAGE2;
	Actuator_t[2].address = ADDBRASSAGE2;
	Actuator_t[2].bobine = BOBBRASSAGE2;
	Actuator_t[2].active = 1;

	Actuator_t[3].type = REMONTER;
	Actuator_t[3].address = ADDREMONTER;
	Actuator_t[3].bobine = BOBREMONTER;
	Actuator_t[3].active = 1;

	Actuator_t[4].type = CHAUFFAGE;
	Actuator_t[4].address = ADDCHAUFFAGE;
	Actuator_t[4].bobine = BOBCHAUFFAGE;
	Actuator_t[4].active = 1;

	Actuator_t[5].type = OSMOLATEUR1;
	Actuator_t[5].address = ADDOSMOLATEUR1;
	Actuator_t[5].bobine = BOBOSMOLATEUR1;
	Actuator_t[5].active = 1;

	Actuator_t[6].type = OSMOLATEUR2;
	Actuator_t[6].address = ADDOSMOLATEUR2;
	Actuator_t[6].bobine = BOBOSMOLATEUR2;
	Actuator_t[6].active = 0;

	Actuator_t[7].type = RAH;
	Actuator_t[7].address = ADDRAH;
	Actuator_t[7].bobine = BOBRAH;
	Actuator_t[7].active = 0;

	Actuator_t[8].type = SUP12_1;
	Actuator_t[8].address = ADDSUP12_1;
	Actuator_t[8].bobine = BOBSUP12_1;
	Actuator_t[8].active = 0;

	Actuator_t[9].type = SUP12_2;
	Actuator_t[9].address = ADDSUP12_2;
	Actuator_t[9].bobine = BOBSUP12_2;
	Actuator_t[9].active = 0;

	Actuator_t[10].type = SUP230_1;
	Actuator_t[10].address = ADDSUP230_1;
	Actuator_t[10].bobine = BOBSUP230_1;
	Actuator_t[10].active = 0;

	Actuator_t[11].type = SUP230_2;
	Actuator_t[11].address = ADDSUP230_2;
	Actuator_t[11].bobine = BOBSUP230_2;
	Actuator_t[11].active = 0;
}

void Actuator_start(uint8_t type) {
	uint8_t val;
	if (Actuator_t[type].active == 1) {
		Actuator_read(Actuator_t[type].address, &val);
		val = val | Actuator_t[type].bobine;
		Actuator_write(Actuator_t[type].address, &val);
	} else {
		while (1)
			; //todo (ORDINATEUR AMELIORATION) A error
	}
}

void Actuator_stop(uint8_t type) {
	uint8_t val;
	Actuator_read(Actuator_t[type].address, &val);
	val = val & !Actuator_t[type].bobine;
	Actuator_write(Actuator_t[type].address, &val);
}

void Actuator_osmo_start(uint8_t type){
	if (Actuator_t[type].type == OSMOLATEUR1) {
		Actuator_start(OSMOLATEUR1);
		HAL_TIM_Base_Start_IT(&htim4);
		gl_osmo1 = 1;
	}
	else {
		Actuator_start(OSMOLATEUR2);
		HAL_TIM_Base_Start_IT(&htim5);
		gl_osmo2 = 1;

	}
}

void Actuator_write(uint8_t add, uint8_t* value) {
	HAL_I2C_Master_Transmit(&hi2c2, add, value, 1, 100);
}

void Actuator_read(uint8_t add, uint8_t* value) {
	HAL_I2C_Master_Receive(&hi2c2, add, value, 1, 100);
}

void Actuator_Satus() {
// a faire
}
