/**
  **************************************************************************************************
  * @file		i2c.h
  * @author		Kerem Yollu & Edwin Koch
  * @date		18.07.2022
  * @version	1.01
  ************************************************************************************************** 
  * @brief		I2C communitation based on the Standart I2C Protocol V7 Defined by NXP/Philips : 
  *				following third Party Protocols based on I2C Bus are not going to be implemented : C-BUS SMBUS PMBUS IPMI DDC ATCA		
  *				This will also not have a I3C support for the forseable futrue. 
  *				
  * **Detailed Description :**
  * 
  *	I2C communitation based on the Standart I2C Protocol V7 Defined by NXP/Philips : 
  *	following third Party Protocols based on I2C Bus are not going to be implemented : C-BUS SMBUS PMBUS IPMI DDC ATCA		
  *	This will also not have a I3C support for the forseable futrue. 
  *
  * @todo 
  * - 26.07.2021 : Implement the DMA  
  * - 26.07.2021 : Implement the Interrupt  
  * - 26.07.2021 : Implement the Sleep/WakeUp  
  * - 26.07.2021 : Implement the Slave opperation  
  **************************************************************************************************
*/

#ifndef _I2C_H_
#define _I2C_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "hardwareDescription.h"
#include "pin.h"

uint32_t i2cCR1;
uint32_t i2cCR2;
uint32_t i2cISR;

/*! Enum of possible I2C opperation modes */
typedef enum{
	i2cModeMaster,			/*!< Master mode : In Master mode, the I2C interface initiates 
							  a data transfer and generates the clock signal. **DEFAULT**			*/ 
	i2cModeMultyMaster,		/*!< Multimaster Mode : In case if more than one master are present 
							  in one I2C bus. In such case each device needs to be able to 
							  cooperate knowing that another device could talking 
							  therefore the bus is busy (Arbirtation). 
							  For More information : https://www.i2c-bus.org/multimaster/		*/
	i2cModeSlave			/*!< Slave mode : A slave device has to always be ready to detect and 
							  process a start condition and to recognize its address			*/
}i2cMode_t; 
	
/*! Enum of possible I2C speeds */
typedef enum{
	i2cSpeedStandart,	/*!< SM 100 kbits/s Standart i2c Speed **DEFAULT**	*/ 
	i2cSpeedFast,		/*!< FM 400 kbits/s									*/
	i2cSpeedFastPlus,	/*!< FM+ 1 Mbits/s									*/
	i2cSpeedHightSpeed, /*!< HS 3.4 Mbits/s									*/
	i2cSpeedUltraFast	/*!< UFM 5 Mbits/s									*/
}i2cSpeed_t;

/*! Enum of possible I2C Adress sizes */
typedef enum{
	i2cAddressSizeSevenBits,	/*!< 7 Bits address size **DEFAULT**	*/ 
	i2cAddressSizeTenBits		/*!< 10 Bits address size				*/
}i2cAddressSize_t;

/*! Enum of possible I2C Address count */
typedef enum{
	i2cAddressCountSingle,	/*!< Only one address for communication **DEFAULT**					*/ 
	i2cAddressCountDual		/*!< Dual addresses for one device respondng to two addresses			*/
}i2cAddressCount_t;

/*! Enum for clock strechning activation. Can only be implmented as Slave 
 * for more information : https://www.i2c-bus.org/clock-stretching/								*/
typedef enum{
	i2cClockStrechingDisable,	/*!< We assume that the master and slave have compatible 
								  Clock frequencies	**DEFAULT**									*/
	i2cClockStrechingEnable		/*!< In situations where an I2C slave is not able to co-operate 
								  with the clock speed given by the master and needs to slow down. 
								  This is done by a mechanism referred to as clock stretching.	*/ 
}i2cClockStreching_t;

/*! Enum for diffenrent wake up methodes wehnin sleep mode */
typedef enum{
	i2cWakeUpDisabled,		/*!< No wake up is possible this is the default mode also means that 
							  the sleep function is not implmentes **DEFAULT**					*/
	i2cWakeUpOnAddressMatch	/*!< Wakes up on address match, this can be harware dependent		*/
}i2cWakeUpTypes_t;

/*! Enum operation mode of the i2c channel */
typedef enum{
	i2cOpperationPolling,	/*!< Polling mode Blocking, i2c communication states are constantly 
							  checked on polling mode so it can be stoped 
							  when interrupts occures **DEFAULT**								*/
	i2cOpperationInt,		/*!< Interrut Mode Non-blocking, i2c communications state changes 	
							  generates an interrupt and can be handeled this way				*/
	i2cOpperationDma		/*!< DMA Mode Non-blocking, I2C communication satets are managed 
							  via Inteerupts and with Direct Memory Access						*/
}i2cOpperationMode_t;

/*! typedef for the i2c states*/
typedef enum
{
	i2cNotInitialized,			/*!< Default Peripheral is not yet Initialized **DEFAULT**		*/
	i2cInitialized,				/*!< I2C CHannle is initilized but not neceserly ready			*/
	i2cReady,					/*!< Peripheral Initialized and ready for use					*/
	i2cBusy,					/*!< An internal process is ongoing								*/
	i2cTransmitting,			/*!< Data Transmission process is ongoing						*/
	i2cRecieving,				/*!< Data Reception process is ongoing							*/
	i2cListening,				/*!< Address Listen Mode is ongoing								*/
	i2cListeningAndTransmitting,/*!< Address Listen Mode and ongoing Data Transmission			*/
	i2cListeningAndRecieveing,	/*!< Address Listen Mode and ongoing Data Reception				*/
	i2cAbort,					/*!< Abort user request ongoing									*/
	i2cTimeout,					/*!< Timeout state												*/
	i2cError					/*!< Error														*/
} i2cState_t;

/*! Struture a an i2c channel with all the required propereties*/
typedef struct i2c_t
{
	i2cCh_t channelNo;					/*!< The harware channel to be used						*/	
	i2cMode_t mode;						/*!< Master, Slave or Multymaster Modes					*/
	uint16_t address;					/*!< First and Main address of the device				*/ 
	uint16_t addressSecond;				/*!< Second address if dual addresse mode is configured	*/
	i2cAddressCount_t addressCount;		/*!< Single or multiple									*/ 
	i2cAddressSize_t addressSize;		/*!< 10 or 7 bit address size							*/
	i2cSpeed_t speed;					/*!< Bus Speed											*/  
	i2cOpperationMode_t opperationMode;	/*!< Blocking or non blocking polling, Int or DMA		*/
	i2cClockStreching_t streching;		/*!< Clock Streching enable onyl in slave mode			*/
	uint32_t timing;					/*!< Specifies the I2C timing. The timings must be 
										  configured in order to guarantee a correct 
										  data hold and setup time, 
										  used in master and slave modes.						*/
	i2cWakeUpTypes_t wakeOn;			/*!< Define on which type of action the i2c channel should 
										  wake up. Only if de prefiral goes to sleep			*/
	i2cState_t state;					/*!< The current sitate of the I2C Bus					*/
}i2c_t;

/***************************************************************************************************
	I2C Configuration functions											
***************************************************************************************************/

/**
 * @brief Initilize the I2C Hardware
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 */
void i2cInit(i2c_t *i2cHardware); 

/**
 * @brief De-Initilize the I2C Hardware
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 */
void i2cDeInit(i2c_t *i2cHardware); 

/**
 * @brief Set the i2c channle to the gievn mode
 * @param Channel is the i2c hardware channel
 * @param mode The mode for i2c : Master Slave or Multymaster 
 */
void i2cSetMode(i2c_t *i2cHardware, i2cMode_t mode);

/**
 * @brief Set the i2c channles mode as Master Slave or Multymaster
 * @param i2cHardware is the i2c hardware channel
 * @param size Is the Adress isze to be used 7 Bit or 10 Bit 
 * @param addressOne The forst address for the device
 * @param addressTwo The second address for the device only if dual address mode is not defined
 */
void i2cSetAddress(i2c_t *i2cHardware, i2cAddressSize_t size, uint16_t addressOne, uint16_t addressTwo);

/**
 * @brief Stets the Communication speed 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param speed the different awailable speeds
 */
void i2cSetSpeed(i2c_t *i2cHardware, i2cSpeed_t speed); 

/**
 * @brief Initiates the opperation mode for the selected i2c Channel 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param opperation define if the i2c channel will opperate on pollin, Interrupt, or DMA modes 
 */
void i2cSetOpperation(i2c_t *i2cHardware, i2cOpperationMode_t opperation);

/**
 * @brief	Sets the finetuning of the Timings for the communication some standards as 
 *			SMBUS have different timing requirements 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param The value to be written in the register. This will heavily depend on the hardware
 */
void i2cSetTimings(i2c_t *i2cHardware, uint32_t timing); 

/**
 * @brief Set the wakeup mode  
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param wake the desider wakeup mode for now i have found only one mode. 
 */
void i2cSetWakeup(i2c_t *i2cHardware, i2cWakeUpTypes_t wake); 

/**
 * @brief Set the timeout to close the i2c wait time if a communication fails. 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param timeout the desider timeout duration in ticks. 
 */
void i2cSetTimeout(i2c_t *i2cHardware, uint8_t timeout);


/**
 * @brief Resets the i2c Periferal to it's inital state.  
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 */
void i2cPeriferalReset(i2c_t *i2cHardware);		

/**
 * @brief Resets the i2c to it's inital state.  
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 */
void i2cReset(i2c_t *i2cHardware);		

/**************************************************************************************************
	I2C Communication functions independen of opperating mode
***************************************************************************************************/

/**
 * @brief	Writes the given amount of data to the selected device. This function will 
 *			automaticaly choose between i2cMasterSend(); or i2cSlaveSend(); 
 *			Depending if the I2C channel was initiated as slave or master. 
 *			this function will adapt himself to the selected oppeartion mode (Polling / Int / DMA) 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data to be written
 * @param dataLenght is the total quantity of 8 bit data to be written.
 */
void i2cWrite(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data, uint8_t dataLenght);

/**
 * @brief Reads the given amount of data to the selected device. This function will 
 *			automaticaly choose between i2cMasterRecieve(); or i2cSlaveRecieve(); 
 *			Depending if the I2C channel was initiated as slave or master. 
 *			this function will adapt himself to the selected oppeartion mode (Polling / Int / DMA) 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data which has been red
 * @paran dataLenght is the total quantity of 8 bit data to be red
 */
void i2cRead(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data, uint8_t dataLenght);

/**
 * @brief	Recieve a Single Byte as master from from the given devices register.
 *			this function will adapt himself to the selected oppeartion mode (Polling / Int / DMA) 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data whic has been red
 */
uint8_t i2cMasterRecieve(i2c_t *i2cHardware, uint8_t devAddress, uint8_t registerAddress, uint8_t *data);
/**
 * @brief	Sends a Single Byte as master to the given devices register. 
 *			this function will adapt himself to the selected oppeartion mode (Polling / Int / DMA) 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the send command will be sent
 * @param registerAddress is the regiter to be written to the device
 * @param data is the data to be sent
 */
void i2cMasterSend(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data);

/**
 * @brief	Recieve a Single Byte as slave from given devices register.
 *			this function will adapt himself to the selected oppeartion mode (Polling / Int / DMA) 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data whic has been red
 */
void i2cSlaveRecieve(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data);

/**
 * @brief	Recieve a Single Byte as slave from the given devices register.
 *			this function will adapt himself to the selected oppeartion mode (Polling / Int / DMA) 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data whic has been red
 */
void i2cSlaveSend(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data);

/**
 * @brief Initiates a Start condition.	
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 */
void i2cSendStart(i2c_t *i2cHardware);


/**************************************************************************************************
	I2C Communication functions Polling / Blocking Mode
***************************************************************************************************/

/**
 * @brief	Recieve a Single Byte in polling mode as master from from the given devices register.
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data whic has been red
 */
void i2cMasterRecievePolling(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data);
/**
 * @brief	Sends a Single Byte in polling mode as master to the given devices register. 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the send command will be sent
 * @param registerAddress is the regiter to be written to the device
 * @param data is the data to be sent
 */
void i2cMasterSendPolling(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data);

/**
 * @brief	Recieve a Single Byte in polling mide as slave from the given devices register.
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data whic has been red
 */
void i2cSlaveRecievePolling(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data);

/**
 * @brief	Recieve a Single Byte in polling mode as slave from the given devices register.
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 * @param registerAddress is the regiter to be red from the device
 * @param data is the data whic has been red
 */
void i2cSlaveSendPolling(i2c_t *i2cHardware, uint16_t *devAddress, uint8_t *registerAddress, uint8_t *data);

/**************************************************************************************************
	I2C Arbitration Functions for Multymaster mode and slaves clock streching 
***************************************************************************************************/
void i2cClockSynchronise();	// I2C Standart : Clock Syncronization
void i2cAbortTransmit();	// I2c Standart : Stop Communication for multimaster mode 
void i2cClockStretch();		// I2C Standart : Optional For Pausing Communication because treatement takes longer than the communication
void i2cArbitration();		// I2C Standart : Arbitration for multimaster mode to define the right master. 
void i2cSoftReset();		// I2C Standart : Software reset not supported by all hardware.
void i2cBusClear();			// I2C Standart : in case if SCL is stuck 


/**************************************************************************************************
	I2C Extra functions that are mot etential for the main functionality
***************************************************************************************************/

/**
 * @brief	This function will scan every for possible addresses to discover devices on the bus.
 *			And write them to the Devices list given to him. This function will not discover more 
 *			devices than what he is told. 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devices list where the discevered devices will be written
 * @param deviceCount Max number of devices to be discovered.
 */
void i2cDiscoverDevices(i2c_t *i2cHardware, uint16_t *devices, uint8_t deviceCount);	   

/**
 * @brief	This function will try to communicate with a device with every speed 
 *			allowed by his hardware to find out the maximum communication sppeed possible.
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to which the read command will be sent
 */
i2cSpeed_t i2cTestDeviceSpeed(i2c_t *i2cHardware, uint16_t *devAddress);	

/**
 * @brief	This function will read the device info register (if awailable) as follows : 
 *			I2c Standart : 3 Bytes (24 bits) | 12 Bits : Manufacturer info | 9 Bits: Part Identification | 3 Bits DIE Rev. 
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 * @param devAddress is the address of the device to be red
 */
uint32_t i2cReadDeviceInfo(i2c_t *i2cHardware, uint16_t *devAddress);	

/**
 * @brief The selected i2c channel is put on sleep.
 * @param i2cHardware is the beforehand declared i2c channel with his opperation modes
 */
void i2cSleep(i2c_t *i2cHardware); 

/**
 * @brief Error handling.
 * @param error The error no generated. 
 */
void i2cThrowError(int16_t error);	// Defined by me : Private error function for error handling

#ifdef __cplusplus
}
#endif

#endif // _I2C_H_
