#include "system_init.h"

#include "ch32v003fun.h"
#include "debug.h"
#include "dhcp.h"
#include "gpio.h"
#include "rs485.h"
#include "spi_dma.h"
#include "systick.h"
#include "timer.h"
#include "uart.h"

#define DHCP_TIMEOUT_MS 15000

void init_system(void) {
  SystemInit();
  init_gpio();
  init_systick();
  tim2_init();
  init_spidma();
  init_uart(UART_BRR_APB1);
  rs485_init(UART_BRR_APB2);
}

int wait_for_dhcp(void) {
  uint32_t start = millis();
  while (dhcp_get_state() != DHCP_STATE_LEASED) {
    if (millis() - start >= DHCP_TIMEOUT_MS) {
      DEBUG_PRINT("DHCP timeout\n");
      return 0;
    }
    dhcp_process();
  }
  return 1;
}
