#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/stm32/f1/i2c.h>
#include <libLHP_UART.h>
#include <libLHP_I2C.h>
#include <stdint.h>

#define I2C_ADDR 0x50
#define I2C_BUF_SZ 1024
#define I2C_EEPROM_SZ 256


void clock_setup(){
rcc_clock_setup_in_hse_8mhz_out_72mhz();
}

void gpio_setup(){
rcc_periph_clock_enable(RCC_GPIOC);
gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ,GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
}

uint8_t memaddr[1];
uint8_t buffer[I2C_BUF_SZ];

int main(){
  uint8_t a=0;
  int i;
  clock_setup();
  gpio_setup();
  GPIOC_ODR = 0;
  
  setup_UART1();
  setup_I2C1();

  
  clrscreen_uart(USART1);
  printstr(USART1,"LHP - Bluepill\r\n"__FILE__ "\r\n"  __DATE__ " - " __TIME__ "\r\n");

   for(i=0;i<256;i++){
     buffer[i] = 0;
   }

  setup_I2C1();
  
  GPIOC_ODR ^= (1<<13);
  // write the adress we want to start at and read 256
  // the 2 first byte of the buffer are the address and will be
  // overwritten
  i2c_transfer7(I2C1,I2C_ADDR, buffer, 2, buffer, 256);


  
  i2c_send_stop(I2C1);

  for ( i = 0; i < 1600000; i++)	/* Wait enough */
    __asm__("nop");


  printstr_blocking(USART1,"---");
  print_uint(USART1,i);
  printstr_blocking(USART1,"---");
  printstr_rn(USART1);
  print_hexdump_str(USART1,buffer,256 );

  while(1){

    if(UART1_received_cmd()){
      GPIOC_ODR ^= (1<<13);
      printstr(USART1,get_receive_buff());
      receive_buff_processed();
      printstr_rn(USART1);

    }
    //usart_send_blocking(USART1, a + '0'); /* USART1: Send byte. */
    a++;
    a%=10;
    //usart_send_blocking(USART1, '\r');
    //usart_send_blocking(USART1, '\n');
    for ( i = 0; i < 1600000; i++)	/* Wait enough to be visible. */
      __asm__("nop");
  }

}
