/* Copyright (c) 2007 Axel Wachtler
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   * Neither the name of the authors nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. */

/* $Id: hif_uart.c,v 1.2 2009/05/05 05:26:16 awachtler Exp $ */

/* === includes ========================================== */
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include "board.h"
#include "ioutil.h"
#include "hif_uart.h"

#if HIF_TYPE_IS_UART

/* === globals =========================================== */
/* temporary uart buffers */
static volatile uint8_t hif_rxbuf[128];
static volatile uint8_t rxhead;
static volatile uint8_t rxtail;


//static volatile uint8_t hif_txbuf[128];

static volatile uint8_t x0 = 42;
static volatile uint8_t hif_txbuf[128];
static volatile uint8_t x1 = 42;

static volatile uint8_t txhead;
static volatile uint8_t txtail;

/* === macros ============================================ */
#define TXBUF_SIZE (sizeof(hif_txbuf))
#define TXBUF_MASK (TXBUF_SIZE-1)


#define RXBUF_SIZE (sizeof(hif_rxbuf))
#define RXBUF_MASK (RXBUF_SIZE-1)

/* === prototypes ======================================== */

/* === functions ========================================= */
void hif_init(const uint16_t baudrate)
{
    HIF_UART_INIT(baudrate);
    HIF_UART_TXIRQ_DI();
    HIF_IO_ENABLE();
    txhead = txtail = 0;
    rxhead = rxtail = 0;

    x0 = x1 = 0xaa;
}

void hif_puts_p(const char *progmem_s)
{
    register char c;
    while ( (c = pgm_read_byte(progmem_s++)) )
    {
      hif_putc(c);
    }
}


void hif_puts(const char *s )
{
uint8_t len, tmp, *p;

#if 1
    len = strlen(s);
    p = (uint8_t *)s;
    tmp = 0;
    do
    {

        tmp = hif_put_blk(p, len);
        p += tmp;
        len -=tmp;
        if (len)
        {
            DELAY_US(2000);
            LED_TOGGLE(0);
        }
    }
    while(len > 0);
#else
    while(*s != 0)
    {
        hif_putc(*s++);
    }
#endif
}

/*
 * Circular memcpy to HIF Buffer
 */
uint8_t hif_put_blk(unsigned char *data, uint8_t size)
{
uint8_t free_size, retsize;
uint8_t newhead, currtail, currhead, b1=0, b2=0;
uint8_t x;

    uint8_t __sreg = SREG; cli();
    /* compute space in uart_tx buffer */
    currtail = txtail;
    currhead = txhead;
    newhead = ((currtail - 1) & TXBUF_MASK);

    if (newhead == currhead)
    {
        /* no space left in circular buffer */
        b1 = 0;
        b2 = 0;
        x = 1;
    }
    else if (currhead > newhead)
    {
        b1 = ((TXBUF_SIZE-currhead) & TXBUF_MASK);
        b2 = newhead;
        x = 2;
    }
    else if (currhead < newhead)
    {
        b1 = ((newhead - currhead) & TXBUF_MASK);
        b2 = 0;
        x = 3;
    }
    free_size = b1 + b2;
    retsize =  (size > free_size) ? free_size : size;

    /* handle block 1*/
    b1 = (b1 > size) ? size : b1;
    if (b1 > 0)
    {
        memcpy((void*)&hif_txbuf[currhead], data, b1);
        data += b1;
        txhead = ((currhead + b1) & TXBUF_MASK);
        size = ((size - b1)  & TXBUF_MASK);
    }

    /* handle block 2*/
    b2 = (size > b2) ?  b2 : size;
    if(b2 > 0)
    {
        memcpy((void*)&hif_txbuf[0], data, b2);
        txhead = (b2);
    }

    HIF_UART_TXIRQ_EI();

    SREG = __sreg;

    return retsize;

}


void hif_putc(unsigned char data)
{
uint8_t newhead;
    newhead = ((txhead + 1) & TXBUF_MASK);

    while (newhead == txtail)
    {

        DELAY_US(2000);
    }
    hif_txbuf[txhead] = data;
    txhead = newhead;
    HIF_UART_TXIRQ_EI();
}


unsigned int hif_getc(void)
{
unsigned int ret = 0x8000;
    if (rxtail != rxhead)
    {
        ret = hif_rxbuf[rxtail];
        rxtail = ((rxtail + 1) & RXBUF_MASK);
    }
    return ret;
}


uint8_t hif_get_blk(unsigned char *data, uint8_t max_size)
{

uint8_t used_size, retsize;
uint8_t newtail, currtail, currhead, b1=0, b2=0;
volatile uint8_t x;

    uint8_t __sreg = SREG; cli();
    /* compute space in uart_tx buffer */
    currtail = rxtail;
    currhead = rxhead;
    newtail = ((currhead - 1) & RXBUF_MASK);

    if (currtail == currhead)
    {
        /* no bytes in circular buffer */
        b1 = 0;
        b2 = 0;
        x = 1;
    }
    else if (currtail > currhead)
    {
        b1 = ((RXBUF_SIZE-currtail) & RXBUF_MASK);
        b2 = currhead;
        x = 2;
    }
    else if (currtail < currhead)
    {
        b1 = ((currhead - currtail) & RXBUF_MASK);
        b2 = 0;
        x = 3;
    }
    used_size = b1 + b2;
    retsize =  (max_size > used_size) ? used_size : max_size;

    /* handle block 1*/
    b1 = (b1 > max_size) ? max_size : b1;
    if (b1 > 0)
    {
        memcpy(data, (void*)&hif_rxbuf[currtail],  b1);
        data += b1;
        rxtail = ((currtail + b1) & RXBUF_MASK);
        max_size = ((max_size - b1)  & RXBUF_MASK);
    }

    /* handle block 2*/
    b2 = (max_size > b2) ?  b2 : max_size;
    if(b2 > 0)
    {
        memcpy(data, (void*)&hif_rxbuf[0], b2);
        rxtail = (b2);
    }

    SREG = __sreg;

    return retsize;

}

#if defined(DOXYGEN)
void HIF_UART_RX_vect();
#else
static volatile uint8_t usr, data, rxovf = 0;
ISR(HIF_UART_RX_vect)
#endif
{
    usr  = HIF_UART_STATUS;
    data = HIF_UART_DATA;

    /** todo handle other uart errors (usr register)*/
    if (rxhead == rxtail)
    {
        rxovf++;
    }
    hif_rxbuf[rxhead] = data;
    rxhead = ((rxhead + 1) & RXBUF_MASK);
}

#if defined(DOXYGEN)
 void HIF_UART_TX_vect();
#else
ISR(HIF_UART_TX_vect)
#endif
{
    usr  = HIF_UART_STATUS;

    /** @todo handle uart errors */

#if 0
    if (txhead != txtail)
    {
        HIF_UART_DATA = hif_txbuf[txtail];
        hif_txbuf[txtail] = '#';
        txtail = ((txtail + 1) & TXBUF_MASK);
    }
    else
    {
        HIF_UART_TXIRQ_DI();
    }
#else

    HIF_UART_DATA = hif_txbuf[txtail];
    hif_txbuf[txtail] = '#';
    txtail = ((txtail + 1) & TXBUF_MASK);
    if (txhead == txtail) /*last byte was send, stop */
    {
        HIF_UART_TXIRQ_DI();
    }


#endif
    LED_TOGGLE(0);
}
#endif
