/*
 * V1.0
 */
 
#include "PCF8574.h"
/*
 * Warning Warning
 *
 * Il existe 2 type de PCF8474 les  PCF8474A et les PCF8474.
 * les PCF8474A on des adresse en 0x4X, les PCF8474 ont des adresse en 0x7X.
 * La différence est faite dans partkeep dans ce projet j'ai utilisé des A
 *
 */

I2C_HandleTypeDef *I2C_PCF8574;

uint8_t ADD_PCF8474[] = { 0x40, 0x42, 0x44, 0x46, 0x48, 0x4A, 0x4C, 0x4E };
//uint8_t ADD_PCF8474[] = {0x70, 0x72, 0x74, 0x76, 0x78, 0x7A, 0x7C, 0x7E};

/** Private Fonction*/
HAL_StatusTypeDef read_I2C_PCF8574(uint8_t add, uint8_t *tab) {
	HAL_StatusTypeDef res;
	int nbTentative = 0;
	while ((res = HAL_I2C_Master_Receive(I2C_PCF8574, add, tab, 1, 1000))!= HAL_OK) {
		nbTentative++;
		if (nbTentative > 3)
			break;
	}
	return res;
}

HAL_StatusTypeDef write_I2C_PCF8574(uint8_t addresse, uint8_t *tab) {
	HAL_StatusTypeDef res;
	int nbTentative;
	while ((res = HAL_I2C_Master_Transmit(I2C_PCF8574, addresse, tab, 1, 1000))!= HAL_OK) {
		nbTentative++;
		if (nbTentative > 3)
			break;
	}
	return res;
}

/** Public Fonction*/

void initPCF8574(I2C_HandleTypeDef *typ) {
	I2C_PCF8574 = typ;
	Write_PCF8574(0, 0);
}

HAL_StatusTypeDef Read_PCF8574(uint8_t addBit, uint8_t* val) {
	return read_I2C_PCF8574(ADD_PCF8474[addBit], val);
}

HAL_StatusTypeDef Write_PCF8574(uint8_t addBit, uint8_t val) {
	return write_I2C_PCF8574(ADD_PCF8474[addBit], &val);
}

HAL_StatusTypeDef Write_One_Bit_PCF8574(uint8_t addBit, uint8_t val, uint8_t Local) {
	uint8_t valInt;
	HAL_StatusTypeDef res;
	res = read_I2C_PCF8574(ADD_PCF8474[addBit], &valInt);
	if (res != HAL_OK)
		return res;
	if (val)
		val = valInt | (val << Local);
	else{
		uint8_t inte=1<<Local;

		inte = ~inte;
		val = valInt & inte;
	}
	return write_I2C_PCF8574(ADD_PCF8474[addBit], &val);
}

