#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/stm32/timer.h>
#include <libLHP_UART.h>
#include <libLHP_D1W.h>
#include <stdint.h>
#include <libopencm3/stm32/f1/nvic.h>
#include <libopencm3/stm32/exti.h>
#include "m31820.h"



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);
}


int main(){  
  clock_setup();
  gpio_setup();
  setup_UART1();
  clrscreen_uart(USART1);
  printstr_blocking(USART1,"LHP - Bluepill\r\n"__FILE__ "\r\n"  __DATE__ " - " __TIME__ "\r\n");

  // /!\ limitations :
  //      you can't use the same pin, even across different ports for different d1w driver number
  //         pins b0 and b1 is fine
  //         pins b0 and a0 is NOT
  //      pins > 4 are not supported, i leave it as an exercise for you to implement
  //      exti9_5_isr and exti15_10_isr, control which pin fired and what timer is running
  D1W_setup(0,GPIOB,0);
  
  uint8_t presence = D1W_detect_presence(0);
  uint64_t rom=0;
  int i,j;

  if(presence){
    i=D1W_search_rom(0);
    j=i;
    while(i){
      i--;
      print_hex_64(USART1,D1W_get_rom(i));
      printstr_rn(USART1);;
    }
  }

    
  printstr_blocking(USART1,"d1w ");
  if(presence){
      printstr_blocking(USART1,"present found ");
      print_uint(USART1,j);
      printstr_blocking(USART1," devices");
  }else{
    printstr_blocking(USART1,"abscent");
  }
  printstr_blocking(USART1,"\r\n");

  while(1){
  m31820_get_temp(0,0);
  D1W_blockfor_ms(0,2000);
  }  



  while(1){
    //    if(presence)
    //  GPIOC_ODR ^= (1<<13);
    for (int i = 0; i < 160000; i++)	/* Wait enough to be visible. */
      __asm__("nop");
  }

}
