// main entry point

#include <string.h>
#include <stdbool.h>

#include "main.h"
#include "sys.h"
#include "server.h"
#include "network.h"
#include "bootloader.h"

// app_header for bootloader (do not modify)
extern void Reset_Handler(void);

__attribute__((used, section(".app_header"))) // used stops the compiler from stripping it
const struct app_header g_app_header = {
  .magic = APP_MAGIC,
  .entry = (uint32_t)&Reset_Handler,
};

int main(void) {
  // initialize physical pins, timers, and clocks
  sys_init();
  
  
  // check bootloader: report whatever the last update attempt recorded
  /*
  const volatile struct crc_header *cdr =
    (const volatile struct crc_header *) CRC_HEADER;

  if (cdr->flag == CRC_FLAG_PASSED) {
    printf("[BOOT] update applied and verified: %lu B\r\n",
           (unsigned long) cdr->slength * FLASH_SECTOR_SIZE);
  } else if (cdr->flag == CRC_FLAG_FAILED) {
    printf("[BOOT] update copied but FAILED verification\r\n");
  }
  */
  

  // configure socket callbacks
  server_init();
  
  // print firmware version
  printf("Using wiznet-serial-bridge firmware version 0.2\r\n");

  // continuously poll sockets and call return path on connection
  while (1) {
    network_sm();
    socket_sm(&XVCPath);
    socket_sm(&UARTPath);
    socket_sm(&eRPCPath);
  }
}
