/**
 * @file wrtd-rt-tdc.c
 *
 * Copyright (c) 2018-2019 CERN (home.cern)
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#include "mockturtle-rt.h"
#include <mockturtle-framework.h>
#include "wrtd-common.h"
#include "hw/fmctdc-direct.h"

#define NBR_CPUS 1
#define CPU_IDX 0
#define NBR_RULES 16
#define NBR_DEVICES 2
#define NBR_ALARMS 1
#define DEVICES_NBR_CHS { 5, 5, 0, 0}
#define DEVICES_CHS_DIR { WRTD_CH_DIR_IN, WRTD_CH_DIR_IN, 0, 0}
#define APP_ID 0x35D2
#define APP_VER RT_VERSION(2, 0)
#define APP_NAME "wrtd-tdc-x2"
#define WRTD_NET_TX 1
#define WRTD_NET_RX 0
#define WRTD_LOCAL_TX 0
#define WRTD_LOCAL_RX 1

#include "wrtd-rt-common.h"

#include "wrtd-tdc.c"

static struct wrtd_tdc_dev tdc0 =
{
        .io_addr = 0x0,
        .ch      = 0,
};

static struct wrtd_tdc_dev tdc1 =
{
        .io_addr = 0x10000,
        .ch      = 5,
};

static inline int wr_link_up(void)
{
        //  Same value for tdc0 and tdc1.
        return tdc_wr_link_up(&tdc0);
}

static inline int wr_time_ready(void)
{
        //  Same value for tdc0 and tdc1.
        return tdc_wr_time_ready(&tdc0);
}

static inline void wr_enable_lock(int enable)
{
        tdc_wr_enable_lock(&tdc0, enable);
        tdc_wr_enable_lock(&tdc1, enable);
}

static inline int wr_aux_locked(void)
{
        return tdc_wr_aux_locked(&tdc0) && tdc_wr_aux_locked(&tdc1);
}

static inline int wr_sync_timeout(void)
{
#ifdef SIMULATION
        return 0;
#else
        return tdc_wr_sync_timeout();
#endif
}

static int wrtd_local_output(struct wrtd_event *ev, unsigned ch)
{
        /* No output.  */
        return 0;
}

static int wrtd_user_init(void)
{
        tdc_init(&tdc0);
        tdc_init(&tdc1);

        wr_enable_lock(0);

        pr_debug("rt-tdc firmware initialized.\n\r");

        return 0;
}

static void wrtd_io(void)
{
        tdc_input(&tdc0);
        tdc_input(&tdc1);
}
