/*
 * main.c
 *
 * Copyright (C) 2022-2023  Sylvain Munaut <tnt@246tNt.com>
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

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

#include <no2usb/usb.h>
#include <no2usb/usb_dfu_rt.h>

#include "led_ctrl.h"
#include "pmu.h"
#include "spi.h"
#include "utils.h"
#include "usb_dev.h"

extern const struct usb_stack_descriptors app_stack_desc;


static void
serial_no_init()
{
	uint8_t buf[8];
	char *id, *desc;
	int i;

	/* Get flash ID */
	flash_unique_id(buf);

	/* Shutdown flash chip */
	flash_deep_power_down();

	/* Overwrite descriptor string */
		/* In theory in rodata ... but nothing is ro here */
	id = hexstr(buf, 8, false);
	desc = (char*)app_stack_desc.str[1];
	for (i=0; i<16; i++)
		desc[2 + (i << 1)] = id[i];
}

void
usb_dfu_rt_cb_reboot(void)
{
	/* Force re-enumeration */
	usb_disconnect();

	/* Boot firmware */
	pmu_sys_reboot(1);
}

//#define USB 1
void main()
{
	/* SPI */
	spi_init();
	serial_no_init();

	/* Enable LEDs */
	led_init();
	led_start();

	/* Enable USB directly */
//#define USB
#ifdef USB
	pmu_usb_enable();
	usb_init(&app_stack_desc);
	usb_dfu_rt_init();
	usb_dev_init();
	usb_connect();
#endif

	/* Main loop */
	while (1)
	{
#ifdef USB
		/* USB poll */
		usb_poll();
		led_poll(false);
#else
		led_poll(true);
#endif
	}
}
