#include "t1001.h"
#include "omw_dbg.h"
#include "t1001_vtimer.h"
#include "t1001_sleep.h"
#include "sys_timeout.h"
#include "hci_core.h"
#include "v0/controller/hci_driver.h"
#include "v0/drivers/hci_driver.h"

#ifdef OMW_HAS_SCH
#include "omw_rtos.h"
#endif

void bt_ready(int err);
void bt_att_tx_polling();

SleepModes local_sleep_mode = SLEEPMODE_CPU_HALT;

static const struct bt_hci_driver drv = {
        #ifndef OMW_COMID_PATCH
        .open = hci_driver_open,
        #else
        .open = hci_driver_open_patch,
        #endif
        .send = hci_driver_send,
        .polling = hci_driver_polling_work,
};

static void hci_driver_init(void)
{
    bt_hci_driver_register(&drv);
}

void omw_host_work_polling()
{
    bt_polling_work();

    bt_att_tx_polling();

    omw_hw_chk_and_en_irq();
}

#ifdef OMW_HAS_SCH
static void omw_host_task(void)
{
    while(1) {
        omw_host_work_polling();

        #ifdef OMW_EN_WDG
        FEED_WTD(OMW_FEED_WDG_TIME);
        #endif
    }
}
#endif

void omw_host_init()
{
    printf("v0 host init!\n");

    omw_set_irq_prio(RTC_IRQn, IRQ_HIGH_PRIORITY);
    omw_enable_irq(RTC_IRQn);

    hci_driver_init();

    bt_enable(bt_ready);

    #ifdef OMW_HAS_SCH
    omw_rtos_add_task(omw_host_task, OMW_RTOS_PRO_UP_MID, OMW_HOST_TASK_SP_SS, OMW_CTRL_ARG_FLAG); //v0 host + v0 ctrl, use OMW_CTRL_ARG_FLAG
    #endif
}
