/*
 * PI-AR035-F1-1 / XC7A35T CVE2 EP11: AN5641 camera SCCB control + 720p HDMI.
 *
 * The FPGA side owns two things:
 *   - a 100 kHz SCCB master that reaches the OV5640 sensor inside the AN5641
 *     module (16-bit register address, 7-bit device address 0x3C),
 *   - a 720p60 TMDS transmitter driven by a colour-bar test picture.
 * This firmware drives the SCCB master through the CAM CSR page at
 * 0x4007_0000 and reports sensor identity plus video-lock state over UART.
 */
#include <stdint.h>

#define UART_TX        (*(volatile unsigned char *)0x10000000u)
#define UART_STATUS    (*(volatile unsigned int  *)0x10000004u)
#define UART_RX        (*(volatile unsigned char *)0x10000008u)

#define GPIO_OUT       (*(volatile unsigned int  *)0x40000000u)
#define GPIO_IN        (*(volatile unsigned int  *)0x40000004u)
#define GPIO_DIR       (*(volatile unsigned int  *)0x40000008u)

#define CAM_ID         (*(volatile unsigned int  *)0x40070000u)
#define CAM_CTRL       (*(volatile unsigned int  *)0x40070004u)
#define CAM_DEV        (*(volatile unsigned int  *)0x40070008u)
#define CAM_REG        (*(volatile unsigned int  *)0x4007000Cu)
#define CAM_WDATA      (*(volatile unsigned int  *)0x40070010u)
#define CAM_RDATA      (*(volatile unsigned int  *)0x40070014u)
#define CAM_STATUS     (*(volatile unsigned int  *)0x40070018u)
#define CAM_VID        (*(volatile unsigned int  *)0x4007001Cu)
#define CAM_GPIO       (*(volatile unsigned int  *)0x40070020u)
#define CAM_FRAMES     (*(volatile unsigned int  *)0x40070024u)
#define CAM_SCLEDGE    (*(volatile unsigned int  *)0x40070028u)

#define ST_BUSY        (1u << 0)
#define ST_DONE        (1u << 1)
#define ST_NACK        (1u << 2)

#define CAM_DEVADDR    0x3Cu          /* OV5640 7-bit SCCB address */

volatile unsigned int g_trap_count;
volatile unsigned int g_trap_cause;
volatile unsigned int g_trap_epc;
volatile unsigned int g_irq_count;
volatile unsigned int g_last_irq;

static unsigned int mcycle_lo(void)
{
    unsigned int v;
    __asm__ volatile ("csrr %0, 0xB00" : "=r"(v));
    return v;
}

static void delay(unsigned int n)
{
    volatile unsigned int i;
    for (i = 0u; i < n; ++i)
        __asm__ volatile ("nop");
}

static void putc(char c)
{
    while (UART_STATUS & 1u)
        ;
    UART_TX = (unsigned char)c;
}

static void puts(const char *s)
{
    while (*s)
        putc(*s++);
}

static void puthex(unsigned int v)
{
    int i;
    for (i = 28; i >= 0; i -= 4)
        putc("0123456789abcdef"[(v >> i) & 0xfu]);
}

static void putdec(unsigned int v)
{
    char buf[12];
    int i = 0;
    if (v == 0u) {
        putc('0');
        return;
    }
    while (v && i < 10) {
        buf[i++] = (char)('0' + (v % 10u));
        v /= 10u;
    }
    while (i > 0)
        putc(buf[--i]);
}

/* One SCCB transaction: write (rd=0) or read (rd=1) the 8-bit value at a
 * 16-bit sensor register address. Returns the STATUS word captured at the end. */
static unsigned int sccb(unsigned int dev, unsigned int reg, unsigned int rd,
                         unsigned int wdata)
{
    unsigned int st;
    int i;

    CAM_CTRL = rd ? 2u : 0u;
    CAM_DEV  = dev & 0x7Fu;
    CAM_REG  = reg & 0xFFFFu;
    CAM_WDATA = wdata & 0xFFu;
    CAM_CTRL = (rd ? 2u : 0u) | 1u;         /* GO one-shot */

    /* busy rises a couple of clocks after GO; give the FSM time to start. */
    for (i = 0; i < 32; ++i)
        __asm__ volatile ("nop");
    while (CAM_STATUS & ST_BUSY)
        ;
    st = CAM_STATUS;
    return st;
}

static unsigned int cam_read(unsigned int reg)
{
    sccb(CAM_DEVADDR, reg, 1u, 0u);
    return CAM_RDATA & 0xFFu;
}

static void print_hex8(unsigned int v)
{
    puthex(v & 0xFFu);
}

int main(void)
{
    unsigned int id;
    unsigned int cam_id;
    unsigned int ok;
    unsigned int vid;
    unsigned int st;
    unsigned int i;
    unsigned int g;
    unsigned int line;
    unsigned int d;
    unsigned int c0;
    unsigned int c1;

    GPIO_DIR = 0x000000ffu;
    GPIO_OUT = 0x000000ffu;                 /* all LEDs off (active low) */

    puts("\r\nEP11 CAMERA SCCB + HDMI 720P60\r\n");
    puts("CAM_BASE=0x40070000 DEV=0x3c\r\n");
    c0 = mcycle_lo();

    id = CAM_ID;
    puts("CAM_CSR_ID=");
    puthex(id);
    puts("\r\n");

    line = (CAM_VID >> 1) & 3u;
    puts("CAM_LINE_SCL_SDA=");
    puthex(line);
    puts("\r\n");

    vid = (CAM_VID & 1u);
    puts("VID_LOCK=");
    putc(vid ? '1' : '0');
    puts("\r\n");

    /* OV5640 chip ID lives at 0x300A/0x300B and reads back 0x5640.
       The module GPIO polarity is undocumented, so sweep both levels. */
    cam_id = 0u;
    st = 0u;
    ok = 0u;
    for (g = 0u; g < 2u; ++g) {
        unsigned int gval = (g == 0u) ? 1u : 0u;
        unsigned int hb;
        CAM_GPIO = gval;
        delay(200000u);
        hb = 0u;
        st = sccb(CAM_DEVADDR, 0x300Au, 1u, 0u);
        if (!(st & ST_NACK))
            hb = CAM_RDATA & 0xFFu;
        if (!(st & ST_NACK))
            st = sccb(CAM_DEVADDR, 0x300Bu, 1u, 0u);
        cam_id = hb << 8;
        if (!(st & ST_NACK))
            cam_id |= (CAM_RDATA & 0xFFu);
        else
            cam_id = hb << 8;
        line = (CAM_VID >> 1) & 3u;
        puts("GPIO=");
        putdec(gval);
        puts(" SENSOR_ID=0x");
        puthex(cam_id);
        puts(" SCCB_STATUS=0x");
        puthex(st);
        puts(" LINE=");
        puthex(line);
        puts("\r\n");
        if (cam_id == 0x5640u) {
            ok = 1u;
            break;
        }
        CAM_GPIO = (gval == 1u) ? 0u : 1u;
        delay(200000u);
    }
    puts("SENSOR_ID=0x");
    puthex(cam_id);
    puts(" SCCB_STATUS=0x");
    puthex(st);
    puts("\r\n");

    /* full SCCB address scan: any ACK proves the sensor bus is alive */
    puts("SCCB_SCAN ACK:");
    line = 0u;
    for (d = 8u; d < 0x78u; ++d) {
        st = sccb(d, 0x300Au, 1u, 0u);
        if (!(st & ST_NACK)) {
            puts(" 0x");
            puthex(d << 1);
            line = line + 1u;
        }
        delay(2000u);
    }
    if (line == 0u)
        puts(" NONE");
    puts("\r\n");
    puts("SCL_EDGES=");
    putdec(CAM_SCLEDGE);
    puts("\r\n");

    ok = (cam_id == 0x5640u);
    if (ok) {
        puts("CAM=DETECTED OV5640 AN5641\r\n");
    } else if (st & ST_NACK) {
        puts("CAM=SCCB_NACK CHECK_MODULE_AND_DEV_ADDR\r\n");
    } else {
        puts("CAM=UNEXPECTED_ID\r\n");
    }

    /* LED1 shows SCCB success, LED2 shows video PLL lock (active low). */
    GPIO_OUT = 0x000000ffu & ~(unsigned int)((ok ? 1u : 0u) | (vid ? 2u : 0u));

    /* Periodic report so the host capture script can log a time series. */
    for (i = 0u; i < 40u; ++i) {
        delay(250000u);                     /* ~5 ms per unit at 50 MHz */
        vid = (CAM_VID & 1u);
        puts("T ");
        putdec(i);
        puts(" VID_LOCK=");
        putc(vid ? '1' : '0');
        puts(" SCCB_OK=");
        putc(ok ? '1' : '0');
        puts(" SENSOR_ID=0x");
        puthex(cam_id);
        puts(" FRAMES=");
        putdec(CAM_FRAMES);
        c1 = mcycle_lo();
        puts(" CYC=");
        putdec(c1 - c0);
        puts("\r\n");
    }

    puts("EP11 DONE\r\n");
    while (1)
        ;
    return 0;
}
