#include "ES28.h"
#include "i2c.h"

//  Pinout:
//  SCL: PB8
//  SDA: PB9
//  Use Alternate function mode AF6

void i2c1_init(void){

    // Configure pins PB8 and PB9
    /* Enable clock access to GPIOB (for PB8 and PB9) */
    RCC->IOPENR |= RCC_IOPENR_GPIOBEN;

    /* Set PB8 and PB9 to alternate function mode (0b10 = 0x2) */
    GPIOB->MODER = (GPIOB->MODER & ~GPIO_MODER_MODE8_Msk) | (GPIO_ALTERNATE << GPIO_MODER_MODE8_Pos);
    GPIOB->MODER = (GPIOB->MODER & ~GPIO_MODER_MODE9_Msk) | (GPIO_ALTERNATE << GPIO_MODER_MODE9_Pos);

    /* Next, select AF6 for these pins. */
    GPIOB->AFR[1] = ((GPIOB->AFR[1]) & ~GPIO_AFRH_AFSEL8_Msk) | (GPIO_AF6 << GPIO_AFRH_AFSEL8_Pos);
    GPIOB->AFR[1] = ((GPIOB->AFR[1]) & ~GPIO_AFRH_AFSEL9_Msk) | (GPIO_AF6 << GPIO_AFRH_AFSEL9_Pos);

    /* Set PB8 and PB9 to open drain */
    GPIOB->OTYPER |= (GPIO_OTYPER_OT8 | GPIO_OTYPER_OT9);

    /* Enable the internal pull-ups on PB8 and PB9. Our devices have their own
       pull-ups, but with no device attached the bus would otherwise float and
       a transaction would never get its NACK. */
    GPIOB->PUPDR = (GPIOB->PUPDR & ~GPIO_PUPDR_PUPD8_Msk) | (GPIO_PULLUP << GPIO_PUPDR_PUPD8_Pos);
    GPIOB->PUPDR = (GPIOB->PUPDR & ~GPIO_PUPDR_PUPD9_Msk) | (GPIO_PULLUP << GPIO_PUPDR_PUPD9_Pos);

    // Configure the i2c module
    /* Enable clock access to I2C1 */
    RCC->APBENR1 |= RCC_APBENR1_I2C1EN;

    /* Enter reset mode (disable peripheral) */
    I2C1->CR1 &= ~I2C_CR1_PE;

    // Timing settings: Standard mode (100kHz) with 12MHz I2CCLK
    I2C1->TIMINGR &= 0x0; // clear timing register
    I2C1->TIMINGR |= (0x2  << I2C_TIMINGR_PRESC_Pos);
    I2C1->TIMINGR |= (0x4  << I2C_TIMINGR_SCLDEL_Pos) | (0x2 << I2C_TIMINGR_SDADEL_Pos);
    I2C1->TIMINGR |= (0xf << I2C_TIMINGR_SCLH_Pos) | (0x13 << I2C_TIMINGR_SCLL_Pos);

    /* Exit reset mode (enable peripheral) */
    I2C1->CR1 |= I2C_CR1_PE;
}

/* Transmit one byte to deviceAddr */
void i2c1_byteWrite(uint8_t deviceAddr, uint8_t data) {
    I2C1->ICR = I2C_ICR_NACKCF | I2C_ICR_STOPCF; // clear leftovers from the last transfer
    I2C1->CR2 = (deviceAddr<<1)
              | (1U << I2C_CR2_NBYTES_Pos)  // will send 1 byte
              | I2C_CR2_AUTOEND             // Send Stop condition after transfer
              | I2C_CR2_START;              // Send Start condition
    while (!(I2C1->ISR & (I2C_ISR_TXIS | I2C_ISR_NACKF))); // ready for data, or nobody answered

    // Send the data
    if (!(I2C1->ISR & I2C_ISR_NACKF)) {
        I2C1->TXDR = data;               // Write the data
    }

    while (!(I2C1->ISR & I2C_ISR_STOPF));   // STOP follows AUTOEND or a NACK
    I2C1->ICR = I2C_ICR_STOPCF | I2C_ICR_NACKCF;
}

/* Receive one byte from deviceAddr */
void i2c1_byteRead(uint8_t deviceAddr, uint8_t *data) {
    I2C1->ICR = I2C_ICR_NACKCF | I2C_ICR_STOPCF; // clear leftovers from the last transfer
    I2C1->CR2 = (deviceAddr<<1)
              | (1U << I2C_CR2_NBYTES_Pos)  // will read 1 byte
              | I2C_CR2_RD_WRN              // ping for reading
              | I2C_CR2_AUTOEND             // Send Stop condition after transfer
              | I2C_CR2_START;              // Send Start condition
    while (!(I2C1->ISR & (I2C_ISR_RXNE | I2C_ISR_NACKF))); // byte arrived, or nobody answered

    // Read the data
    if (!(I2C1->ISR & I2C_ISR_NACKF)) {
        *data = I2C1->RXDR;              // Read the data
    }

    while (!(I2C1->ISR & I2C_ISR_STOPF));   // STOP follows AUTOEND or a NACK
    I2C1->ICR = I2C_ICR_STOPCF | I2C_ICR_NACKCF;
}

/* Write n bytes to a register location on deviceAddr */
void i2c1_memWrite(uint8_t deviceAddr, uint8_t registerAddr, uint8_t nbytes, uint8_t *data) {
    I2C1->ICR = I2C_ICR_NACKCF | I2C_ICR_STOPCF;  // clear leftovers from the last transfer
    I2C1->CR2 = (deviceAddr<<1)
              | ((nbytes+1) << I2C_CR2_NBYTES_Pos) // n+1 to account for first sending the registerAddr
              | I2C_CR2_AUTOEND                    // Send Stop condition after transfer
              | I2C_CR2_START;                     // Send Start condition

    // Send register address
    while (!(I2C1->ISR & (I2C_ISR_TXIS | I2C_ISR_NACKF))); // ready for data, or nobody answered
    if (!(I2C1->ISR & I2C_ISR_NACKF)) {
        I2C1->TXDR = registerAddr;
    }

    // Send data
    for (uint8_t i = 0; i < nbytes; i++) {
        while (!(I2C1->ISR & (I2C_ISR_TXIS | I2C_ISR_NACKF))); // ready for next byte, or refused
        if (!(I2C1->ISR & I2C_ISR_NACKF)) {
            I2C1->TXDR = data[i];                  // Write the data
        }
    }

    while (!(I2C1->ISR & I2C_ISR_STOPF));   // STOP follows AUTOEND or a NACK
    I2C1->ICR = I2C_ICR_STOPCF | I2C_ICR_NACKCF;
}

/* Read n bytes from a register location on deviceAddr */
void i2c1_memRead(uint8_t deviceAddr, uint8_t registerAddr, uint8_t nbytes, uint8_t *data) {
    // Ping target address for writing 1 byte (the register address within target from which to read)
    I2C1->ICR = I2C_ICR_NACKCF | I2C_ICR_STOPCF;  // clear leftovers from the last transfer
    I2C1->CR2 = (deviceAddr<<1)
              | (1U << I2C_CR2_NBYTES_Pos)         // for registerAddr
              | I2C_CR2_START;                     // Send Start condition; no AUTOEND, keep the bus

    // Send register address
    while (!(I2C1->ISR & (I2C_ISR_TXIS | I2C_ISR_NACKF))); // ready for data, or nobody answered
    if (!(I2C1->ISR & I2C_ISR_NACKF)) {
        I2C1->TXDR = registerAddr;
    }
    while (!(I2C1->ISR & (I2C_ISR_TC | I2C_ISR_NACKF)));   // address sent and bus held, or refused

    // Repeated start, with read request for n bytes
    if (!(I2C1->ISR & I2C_ISR_NACKF)) {
        I2C1->CR2 = (deviceAddr<<1)
                  | (nbytes << I2C_CR2_NBYTES_Pos) // will read n bytes
                  | I2C_CR2_RD_WRN                 // ping for reading
                  | I2C_CR2_AUTOEND                // Send Stop condition after transfer
                  | I2C_CR2_START;                 // Send (repeated) Start condition
    }

    // Read the data
    for (uint8_t i = 0; i < nbytes; i++) {
        while (!(I2C1->ISR & (I2C_ISR_RXNE | I2C_ISR_NACKF))); // byte arrived, or refused
        if (!(I2C1->ISR & I2C_ISR_NACKF)) {
            data[i] = I2C1->RXDR;                  // Read the data
        }
    }

    while (!(I2C1->ISR & I2C_ISR_STOPF));   // STOP follows AUTOEND or a NACK
    I2C1->ICR = I2C_ICR_STOPCF | I2C_ICR_NACKCF;
}
